Calling Base Class Constructors From Derived Class

Hey Guys,

I'm having some difficulties in understanding the topic which I stated above.Can anyone here provide some good examples and references which will help me in future.

Thanks.
There is no easy way to do this, as classes can be derived from multiple other classes. There is no way to tell with a single command in what super class you want to call the constructor.

If you make a function that initializes everything, I believe that you can use ((BaseClass) instance_of_derived_class).init();. I am not positive on this one though.
There is no easy way to do this, as classes can be derived from multiple other classes. There is no way to tell with a single command in what super class you want to call the constructor.


If you couldn't do this, how would you make a class work like this:
1
2
3
4
5
6
7
8
9
class Base {
public:
    Base(int x) {}
};

class Derv : public Base {
public:
    Derv(int x) {} //how to call Base(int x) here?
}


To call it, you must use an initializer list.
#include <iostream>
using namespace std;

class MyPoint
{
int x,y;

public:
double get1()
{
cout<<"Enter a value for x"<<endl;
cin>>x
}

double get2()
{
cout<<"Enter a value for y"<<endl;
cin>>y;
}

double difference()
{
double get;
return get=x-y;
}


};

class ThreeDPoint:public MyPoint
{
int z;

ThreeDPoint(int a):MyPoint(x,y)
{
a=0;
z=a;



}

}
## in the example how I want to make the value x and y =0 by calling the base class constructor

1
2
3
4
5
6
7
8
9
10
11
12
class MyPoint
{
private:
    int x,y;

public:
    MyPoint(int initialX = 0, int initialY = 0) : // Take 0 by default
        x(initialX),
        y(initialY)
    {}
    // ...
};


1
2
3
4
5
6
7
8
9
10
11
12
13
class ThreeDPoint : public MyPoint
{
private:
    int z;

public:
    ThreeDPoint(int a) :
        MyPoint(0, 0),
        z(0)
    {
    }
    // ...
};

There are two ways. Either you explicitly call a base constructor in mem-initializer list or you use a using declaration of the base constructor name in the derived class.

EDIT: Here is an example but you should find the compiler that will compile the code because not all compilers support inheriting constructors.:)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
 
struct Base
{
    Base( int i ) : x( i ) {}
    int x;
};
 
struct Derived : Base
{
    using Base::Base;
    Derived() : Base( 0 ) {}
};
 
int main()
{
    Derived d1;
    
    std::cout << "d1.x = " << d1.x << std::endl;
    
    Derived d2( 10 );
    
    std::cout << "d2.x = " << d2.x << std::endl;
    
    return 0;
}
Last edited on
Topic archived. No new replies allowed.