inheritance in c++ different constructor code example

Example 1: c++ base constructor

class Derived: public Base
{
public:
    double m_cost;
 
    Derived(double cost=0.0, int id=0)
        : Base{ id }, // Call Base(int) constructor with value id!
            m_cost{ cost }
    {
    }
 
    double getCost() const { return m_cost; }
};

Example 2: multiple inheritance in c++

#include<iostream> 
using namespace std; 

class A 
{ 
public: 
A() { cout << "A's constructor called" << endl; } 
}; 

class B 
{ 
public: 
B() { cout << "B's constructor called" << endl; } 
}; 

class C: public B, public A // Note the order 
{ 
public: 
C() { cout << "C's constructor called" << endl; } 
}; 

int main() 
{ 
	C c; 
	return 0; 
}

Tags:

Cpp Example