Originally Posted by
Bird Killer
http://www.rafb.net/paste/results/KJa8Yx24.html
Alright thanks for the help, I learned a few points:
I have to declare methods in the derived classes if its base class declares it as a virtual function
I cannot initialize base class methods in the derived class's initializer list (I wonder why?)
What you should be doing is creating a constructor for Client that initializes those values in the base class (with the initializer list), then calling that Client constructor from the derived classes.
The reason you cannot use base class members inisde the derived class initializer list is because each member can be initialized only once. What you put in the initializer list is what determines which constructor to call. If you don't put anything in the initializer list, the default constructor is called. So in your example, when the base class is constructed, its members are default constructed, and then if you tried to add them to the derived class initializer list, they would have a constructor called again, which is obviously illegal.
These two classes construct themselves in the same way:
Code:
class Base1
{
private:
std::string name;
};
class Base2
{
private:
std::string name;
public:
Base2() : name() { }
};
They both call the default constructor for the string member.
Similarly, these two derived classes are constructed the same:
Code:
class Derived1 : public Base1
{
};
class Derived2 : public Base2
{
public:
Derived2() : Base2() { }
};
Again, in both cases the base class's string member is default constructed. So to truly initialize a base class member, you have to use the base class's initializer list and then call that constructor from the derived class:
Code:
class Base
{
private:
std::string name;
public:
Base(const std::string& n) : name(n) { }
};
class Derived : public Base
{
public:
Derived(const std::string& n) : Base(n) { }
};
Note that I used private instead of protected there. In general it is better design to leave all members private, and provide an interface to those members for derived classes.