Archive for the ‘class using in c++’ Category

inherited from the base class

July 30th, 2010 c# No comments

In principle, a derived class inherits every member of a base class except:

* its constructor and its destructor
* its operator=() members
* its friends

Although the constructors and destructors of the base class are not inherited themselves, its default constructor (i.e., its constructor with no parameters) and its destructor are always called when a new object of a derived class is created or destroyed.

If the base class has no default constructor or you want that an overloaded constructor is called when a new derived object is created, you can specify it in each constructor definition of the derived class:

derived_constructor_name (parameters) : base_constructor_name (parameters) {…}

For example:

// constructors and derived classes
using namespace std;

class mother {
mother ()
{ cout << "mother: no parameters\n"; }
mother (int a)
{ cout << "mother: int parameter\n"; }

class daughter : public mother {
daughter (int a)
{ cout << "daughter: int parameter\n\n"; }

class son : public mother {
son (int a) : mother (a)
{ cout << "son: int parameter\n\n"; }

int main () {
daughter cynthia (0);
son daniel(0);

return 0;

mother: no parameters
daughter: int parameter

mother: int parameter
son: int parameter

Notice the difference between which mother’s constructor is called when a new daughter object is created and which when it is a son object. The difference is because the constructor declaration of daughter and son:

daughter (int a) // nothing specified: call default
son (int a) : mother (a) // constructor specified: call this

Categories: class using in c++ Tags: