Skip to content

Instantly share code, notes, and snippets.

@dflemstr
Created February 15, 2010 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dflemstr/304826 to your computer and use it in GitHub Desktop.
Save dflemstr/304826 to your computer and use it in GitHub Desktop.
#include "example.h"
Example::Example(int someInt, const std::string &someString)
: _someInt(someInt), //Assign _someInt
_someString(someString) //Copy the whole string to _someString
{
}
const std::string &Example::someString() const
{
return _someString;
}
int Example::someInt() const
{
return _someInt;
}
void Example::setSomeInt(int value) //int is passed by-value, so no need to const
{
_someInt = value;
}
void Example::setSomeString(const std::string &value) //This is a string reference; make const
{
//This will *copy* the string to our private variable.
//So, we don't have to make _someString const, like we would have had to
//if we had made _someString into a reference too.
_someString = value;
}
#ifndef EXAMPLE_H
#define EXAMPLE_H
#include <string>
class Example
{
public:
explicit Example(
//Passed by-val, no need to const
int someInt,
//Passed by-ref, so const. Tells the caller that *we* won't modify the string.
const std::string &someString);
//This does just "return _someString;", and doesn't modify *this.
//So, make it const.
const std::string &someString() const;
//Ditto.
int someInt() const;
//This modifies *this, so don't const
void setSomeInt(int value);
//This also modifies *this
void setSomeString(const std::string &value);
private:
int _someInt;
std::string _someString;
};
#endif // EXAMPLE_H
#include "example.h"
#include <iostream>
int main(int, char **)
{
const Example ex(42, "Hello"); //Immutable (constant) class!
// Compilation error:
//ex.setSomeInt(72);
//ex.setSomeString("Bye.");
//This is OK, since e.g. "ex.someString()" is a const operation
std::cout << ex.someString() << std::endl; //prints Hello!
std::cout << "The answer: " << ex.someInt() << std::endl; //prints 42
Example ex2(ex); //Make a mutable copy
ex2.setSomeInt(750); //OK: ex2 is not const
std::cout << ex2.someString() << std::endl; //prints Hello!
std::cout << "The answer: " << ex2.someInt() << std::endl; //prints 750
const Example *const ex3(new Example(666, "nil"));
std::cout << ex3->someInt() << std::endl; //prints 666
//Does not work:
//ex3->setSomeInt(54);
Example *const ex4(new Example(*ex3)); //Make mutable copy
ex4->setSomeInt(65);
std::cout << ex4->someInt() << std::endl; //prints 65
//Oh, and we mustn't forget (even though it doesn't matter :P):
delete ex3;
delete ex4;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment