constructor derived class c++ 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: constructor derived class c++

#include <iostream>
using namespace std;

class Complex
{
    int a, b;
    
public:

    Complex(int x, int y)
    {
        a = x;
        b = y;
    }

    Complex(int x)
    {
        a = x;
        b = 0;
    }

    Complex()
    {
        a = 0;
        b = 0;
    }

    void printNumber()
    {
        cout << "Your number is " << a << " + " << b << "i" << endl;
    }

};

int main()
{
    Complex c1(4, 6), c2(4), c3;

    c1.printNumber();
    c2.printNumber();
    c3.printNumber();

    return 0;
}

Tags:

Cpp Example