Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Base Class Constructors in C++

Tags:

c++

Is this a legal way of calling a base class constructor.

The Base Class is as follows

class base_class
{
    public:
    base_class(int x, int y);    
    protected:
    int a;
    int b;
};

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

The Derived class is a follows

class derived_class: public base_class
{
    public:
    derived_class(int x,int y,int z);
    protected:
    int c;
};
derived_class:: derived_class(int x,int y,int z):base_class(x,y)  /*Edited and included the scope resolution operator*/
{
    c=z;
}

Is this way of defining a derived class constructor legal in C++, if yes how is the base class constructor called?

like image 760
Jay K Avatar asked Nov 20 '25 13:11

Jay K


1 Answers

Assuming you meant

derived_class::derived_class(int x,int y,int z):base_class(x,y)   
//            |
//     scope resolution operator

then yes. It's not only a legal way, it's the only way to explicitly call a base constructor for the current object.

Unless you do this, the default constructor is called implicitly. In your case, the base class doesn't have a default constructor, so you'd get a compiler error.

like image 83
Luchian Grigore Avatar answered Nov 23 '25 04:11

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!