class Animal
{
public:
Animal(const string& name) : name(name) {}
virtual string talk() = 0;
const string name;
};
class Cat : public Animal
{
public:
Cat(const string& name) : Animal(name) {}
string talk() { return "Meow!"; }
};
class Dog : public Animal
{
public:
Dog(const string& name) : Animal(name) {}
string talk() { return "Arf! Arf!"; }
};
[C++] Calling superclass constructor - a quick question
The code below is from Wikipedia:
I understand that the sub-classes have ": Animal(name)" after their construction prototype to call their super-class constructor along with their own constructor. But why does the super-class constructor has ": name(name)" part? The super-class has no parent class, why does it use that syntax? Is it for initializing the string object 'name'? If so, why does it use such a syntax instead of initializing it just by using its constructor?
It's called initialization lists, and it's better to initialize objects like that. When the constructor body is run, objects will already have been initialized with the default constructor, and you must assign them afterward. With the initialization list you skip that, and directly construct them using the constructor you want. Also, const objects can't be modified in the constructor body.
See http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6 for more information.
See http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6 for more information.
It is as Erik said, and it is also used to initialize members which are references :
class MyClass{public: MyClass(std::string& myRefToObj) : m_myRefToObj(myRefToObj) {} std::string& m_myRefToObj;};
In your constructor
the : name(name) calls the constructor of the string member variable called "name"
it would be the same to do
I don't really remember what's exactly the difference between the two methods, but usually when you want to initialize a member and you don't need any logic to do it (if, loops or function calls)people tend to use the first method.
[EDIT]wow I'm late. yeah the const/reference thing makes sense
Animal(const string& name) : name(name) {}
the : name(name) calls the constructor of the string member variable called "name"
it would be the same to do
Animal(const string& name) {name = name;}
I don't really remember what's exactly the difference between the two methods, but usually when you want to initialize a member and you don't need any logic to do it (if, loops or function calls)people tend to use the first method.
[EDIT]wow I'm late. yeah the const/reference thing makes sense
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement