Aris Koutsoukis
Aris Koutsoukis

Reputation: 37

Derived object created without having default constructor

I was doing a small test in a site and I run to this problem.

#include<iostream.h> 
class Base
{
    int x, y, z; 
    public: 
    Base()
    {
        x = y = z = 0;
    }
    Base(int xx, int yy = 'A', int zz = 'B')
    {
        x = xx;
        y = x + yy;
        z = x + y;
    }
    void Display(void)
    {
        cout<< x << " " << y << " " << z << endl;
    }
};
class Derived : public Base
{
    int x, y; 
    public:
    Derived(int xx = 65, int yy = 66) : Base(xx, yy)
    {
        y = xx; 
        x = yy;
    }
    void Display(void)
    {
        cout<< x << " " << y << " ";
        Display(); 
    }
};
int main()
{
    Derived objD;
    objD.Display();
    return 0; 
}

I choose the compile error choice because we are instantiating a Derived object with zero argument's for the constructor and we have defined one which takes 2 arguments. As far as I know if we define a constructor our self the compiler doesn't provide the default one any more. I run the code and it compiled correctly. Can someone please explain it made me really confused.

Upvotes: 1

Views: 52

Answers (2)

code_fodder
code_fodder

Reputation: 16331

this is because you have default parameters in your c'tor meaning if you don't pass parameters in then it defaults the parameters. Your constructor can handle 0,1 or 2 parameters.

If you change:

Derived(int xx = 65, int yy = 66) : Base(xx, yy)

to

Derived(int xx, int yy) : Base(xx, yy)

then your compile will fail

additionally

Since your c'tor can be used with just one argument you probably want to do use explicit:

explicit Derived(int xx = 65, int yy = 66) : Base(xx, yy)

This disallows implicit conversion occuring when you don't expect them. Explicit conversion is still possible. If you remove the default values then you will not need to do this because your c'tor can then only take 2 parameters.

Upvotes: 3

CiaPan
CiaPan

Reputation: 9570

The Derived class doeasn't have a parameterless constructor, but it has a constructor which can be called without parameters: a call to Derived::Derived() gets resolved as Derived::Derived(65, 66) by default parameter values.

Upvotes: 1

Related Questions