I know and I have read many threads to call a base class constructor from a Derived class, But I wanted to implement it using Delegating constructors
Here is my code
The error states
"A delegating constructor cannot have other mem-initializers"
#include <iostream>
using namespace std;
// Shivang101
class Base
{
private:
int value;
public:
Base() : value{0}
{
cout << "Base no args constructor called" << endl;
}
Base(int x) : value{x}
{
cout << "Base (int) overloaded constructor called" << endl;
}
~Base()
{
cout << "Base Destructor called" << endl;
}
};
class Derived : public Base
{
private:
int testing_value;
int doubled_value;
// using Base ::Base;
public:
Derived() : Derived{0, 0}
{
cout << "NO arg constructor called" << endl;
};
// In the below line I'm Trying a call the base class constructor but getting error
Derived(int testing_val) : Base{testing_val}, Derived{testing_val, 0}
{
cout << "One arg constructor called" << endl;
}
Derived(int testing_val, int doubled_val) : testing_value{testing_val}, doubled_value{doubled_val}
{
cout << "Delegating constructor/ overloaded called" << endl;
}
~Derived()
{
cout << "Derived destructor called" << endl;
}
};
int main()
{
Derived d{1000};
return 0;
}
I wanted to call my base class constructor and initialize the "value" in Base class as "1000" and initialize the "testing_*value" and "doubled_*value" in the Derived class as "1000" and "2000" respectively
A constructor is responsible for initializing all members and base subobjects.
A delegating constructor delegates to a different constructor.
It cannot be both. Either you delegate elsewhere or you initialize members and base subobjects.
Quoting from cppreference:
I suppose you can rearrange the constructors to achieve desired effect. Though I don't see how it can be done without implementing one more constructor or change the way of delegating, because currently the one taking two arguments calls the default constructor of
Base
, but the one delegating to it attempts to callBase{testing_val}
.