Class Contructor

I know that an object of another class can be initiated using the method below but this is a variable that was declared and not a function. I don't fully understand the code below.

 
Pet(string name) : name(name) {}


Full class:

1
2
3
4
5
6
7
8
9
10
11

class Pet {
protected: string name;
public:	   Pet(string name) : name(name) {}
	   virtual void MakeSound(void) { cout << name << " is silent :(" << endl; }
};
class Dog : public Pet {
public:	Dog(string name) : Pet(name) {}
	void MakeSound(void) { cout << name << " says: Woof!" << endl; }
};

You can make life easier for your self if you give the arguments and member variables different but similar names.

std::string should be passed by reference.

public: Pet( std::string& nameArg) : name(nameArg) {}

with the const, it should not be there in the class declaration, but we do put it there in the function definition. This so someone reading the class declaration can see: "oh I can send it a string", but the const in the definition means it's value won't be changed inside the function.

1
2
3
4
Pet::Pet (const std::string& nameArg) 
      :
       name(nameArg)
{}


Note it is not an error to have name(name) , just that name(nameArg) is less confusing.

This form: name(nameArg) is called direct initialisation.

http://en.cppreference.com/w/cpp/language/initialization
closed account (48T7M4Gy)
or name(aName)
Topic archived. No new replies allowed.