I have a Base class that I can't modify the source code. I make a derived class from it and I am trying to make a no-argument constructor for this derived class. The problem is that I can't define the constructor for two reasons:
There is not a non-argument constructor defined for the base class to use it.
I can't pass a default value for the constructor of the base.
class base
{
public:
base (A arg)
{
}
};
class derived : public base
{
public:
derived () : base (arg) //ERROR
{
}
};
Is there a solution to define a non-argument constructor for the derived class?
Cordialement,
Since you cannot change the base class the only option left is to pass an argument to its constructor. You can do this quite easily by constructing a temporary instance of A and passing it to the base class in your ctor initialized list of derived classes.
derived::derived () : base (A())
{
}
In the code above base(A()) will create a temporary instance of A and pass it to the constructor of base.
Related
I have a situation where the top class requires a parameter while none of the child classes does. Some class:
class SuperClass {
public:
SuperClass(const int parameter);
}
And it's child:
class NoParametersInConstructorClass : public SuperClass {
public:
// This will cause an error:
// error: no matching function for call to 'SuperClass::SuperClass(const int)'
NoParametersInConstructorClass() : someText("Hello") {};
private:
std::string someText
}
Now the problem I am facing is that I do have an initializer list, but I find it tedious to rewrite the arguments in all child classes. I am lazy I know. I would like this to work without explicitly defining it:
// Works even though NoParametersInConstructorClass(const int) isn't defined
NoParametersInConstructorClass variable(66);
Of course, if there is no way, there is no way, but is there?
All the derived classes have to pass some value to the base class. It will be easy for the derived classes to have a default constructor in the base class that is in the protected section. You can initialize the member data of the base class that makes sense for the derived classes.
class SuperClass {
public:
SuperClass(const int parameter);
protected:
SuperClass() : SuperClass(10) {} // Delegate to the other constructor.
}
If your problem is that you have a certain set of children, all of which need the SuperClass constructor to be called with the same default argument, all you need to do is to introduce an intermediary with no-argument constructor, which would call the SuperClass::SuperClass with the magic number.
Make the parameter defaulted.
class SuperClass {
public:
SuperClass(const int parameter = DEFAULT);
}
You can then chose to include the constructor in your initialize list, or use the default.
Default value:
class NoParameterChildDefault : public SuperClass
{
public:
NoParameterChildDefault() : someText("Hello") { ... } // uses value DEFAULT.
};
Explicit Value:
class NoParameterChildExplicit : public SuperClass
{
public:
NoParameterChildExplicit() : SuperClass(5), someText("Hello") { ... } // uses value '5'.
};
You may wanna change your default child constructor:
class NoParametersInConstructorClass : public SuperClass {
public:
NoParametersInConstructorClass(int n =0) : SuperClass(n)someText("Hello") {};
private:
std::string someText
}
This way both NoParametersInConstructorClass variable(66); and NoParametersInConstructorClass variable; will work.
To answer your edited question:
You can use the using keyword to make the derived class use the base class constructor:
class NoParametersInConstructorClass : public SuperClass {
public:
using SuperClass::SuperClass;
NoParametersInConstructorClass() : someText("Hello") {};
private:
std::string someText
}
You have to somehow define a constructor for the derived class. You can't just call the base class constructor for the derived class without the using statement.
Let's suppose you can't (or you won't) modify the base class to add a default constructor, you have to call the constructor of the base class in its valid form (with argument) in initialization list of every derived class (like here)
I have something like this:
Class Base
{
public:
Base();
protected:
someType myObject;
}
Class Child:public someNamespace::Base
{
//constructor
Child(someType x):myObject(x){}
}
Class Child, and Base are in 2 different namespaces...
Compiler complains that my Child class does not have a field called myObject
Anyone know why? Is it because its illegal to populate a Base member from a Child constructor?
Thanks
You cannot initialize the inherited member like that. Instead, you can give the base class a constructor to initialize that member, then the derived class can call that constructor.
class Base
{
public:
Base(someType x) : myObject{x} {}
protected:
someType myObject;
}
class Child : public Base
{
public:
//constructor
Child(someType x) : Base(x) {}
}
In general, a class should be responsible for initializing its own members.
The problem here is that you are initializing your inherited myObject in the initialization list. When an object of the derived class is created, before entering the body of the constructor of the derived class the constructor of the base class is called (by default, if base class has default or no parameter constructor, otherwise you have to explicitly call the constructor in the initialization list).
So, when you do :: Class Child:public someNamespace::Base your constructor for the base class has not yet been called, which is why your compiler complains :: Child class does not have a field called myObject, that is you are actually trying to assign a value to something which has not yet been declared and defined! It will get defined after the constructor the Base class enters its execution.
So, your Child class constructor will look something like this ::
Child(someType x) {
myObject = x;
}
Working ideone link :: http://ideone.com/70kcdC
I found this point missing in the answer above, so I thought it might actually help!
I have an abstract base class that needs some objects passed to its constructor to initialize its members. But I would like to get rid of passing those objects through the derived class constructor.
class Derived : public Base
{
public:
Derived(type one, type two, type three) : Base(one, two, three)
{
// ...
The objects passed to the base classes are the same instances for all created derived classes. Is there a way to bind them to the base class' constructor, so that I don't have to forward them through the derived class' constructor?
// do some magic
// ...
class Derived : public Base
{
// no need for an explicit constructor anymore
// ...
In C++11 you can inherit constructors to the base class. It seems this would roughly do what you need:
class derived
: public base {
public:
using base::base;
// ...
};
#include<iostream>
using namespace std;
class base
{
protected:
int a;
public:
base(int i)
{
a=i;
}
};
class derived :protected base
{
public:
derived(){}
void show()
{
cout<<a;
}
};
int main()
{
base obj(2);
derived obj1;
obj1.show();
return 0;
}
Why is this program giving error as In constructor derived::derived():
error: no matching function for call to base::base()
Please explain. As i have read in stackoverflow that in case of inheriting as protected, protected members of base class became protected member of derived class. If I am wrong then please share a good link to clear my misconception
Once you define a constructor for any class, the compiler does not generate the default constructor for that class.
You define the parameterized constructor(base(int i)) for base and hence the compiler does not generate the no argument constructor for base.
Resolution:
You will need to define a constructor taking no arguments for base yourself.
Add this to your base class:
base():a(0)
{
}
EDIT:
Is it needed to define default constructor to every class? Or is it necessary to have the constructor that matches the derived type also present in base type?
The answer to both is NO.
The purpose of constructors in C++ is to initialize the member variables of the class inside the constructor. As you understand the compiler generates the default constructor(constructor which takes no arguments) for every class.
But there is a catch, If you yourself define (any)constructor(one with parameters or without) for your class, the compiler does not generate the default constructor for that anymore. The compiler reasoning here is "Huh, this user writes a constrcutor for his class himself, so probably he needs to do something special in the constructor which I cannot do or understand", armed with this reasoning the compiler just does not generate the default no argument constructor anymore.
Your code above and you assume the presence of the default no argument constructor(When derived class object is created). But since you already defined one constructor for your base class the compiler has applied its reasoning and now it refuses to generate any default argument constructor for your base class. Thus the absence of the no argument constructor in the base class results in the compiler error.
You must give a value to the base constructor:
class Derived : protected base
{
public:
Derived() : base(0)
{
}
};
Depending on your implementation, give the value to the base constructor. However, you may want the Derived constructor to take also int as an argument, and then pass it to the base one.
You need to implement an empty constructor in base or invoke the defined base(int) constructor explicitly from derived c-tor. Without it, when derived c'tor is activated,
it is trying to invoke base() [empty c'tor], and it does not exist, and you get your error.
You haven't defined a default constructor for Base..
When you instantiate an instance of Derived, it will call the Derived() constructor, which will in turn try to call the Base() default constructur which doesn't exist as you haven't defined it.
You can either declare an empty constructor for base Base::Base() or call the existing one as below:
#include<iostream>
using namespace std;
class base
{
protected:
int a;
public:
base(int i)
{
a=i;
}
};
class derived :protected base
{
derived(): Base(123) {} --this will call the Base(int i) constructor)
void show()
{
cout<<a;
}
};
int main()
{
base obj(2);
derived obj1;
obj1.show();
return 0;
}
Lately, I have done much programming in Java. There, you call the class you inherited from with super(). (You all probably know that.)
Now I have a class in C++, which has a default constructor which takes some arguments. Example:
class BaseClass {
public:
BaseClass(char *name); ....
If I inherit the class, it gives me the warning that there is no appropriate default constructor available. So, is there something like super() in C++, or do I have to define a function where I initialize all variables?
You do this in the initializer-list of the constructor of the subclass.
class Foo : public BaseClass {
public:
Foo() : BaseClass("asdf") {}
};
Base-class constructors that take arguments have to be called there before any members are initialized.
In the header file define a base class:
class BaseClass {
public:
BaseClass(params);
};
Then define a derived class as inheriting the BaseClass:
class DerivedClass : public BaseClass {
public:
DerivedClass(params);
};
In the source file define the BaseClass constructor:
BaseClass::BaseClass(params)
{
//Perform BaseClass initialization
}
By default the derived constructor only calls the default base constructor with no parameters; so in this example, the base class constructor is NOT called automatically when the derived constructor is called, but it can be achieved simply by adding the base class constructor syntax after a colon (:). Define a derived constructor that automatically calls its base constructor:
DerivedClass::DerivedClass(params) : BaseClass(params)
{
//This occurs AFTER BaseClass(params) is called first and can
//perform additional initialization for the derived class
}
The BaseClass constructor is called BEFORE the DerivedClass constructor, and the same/different parameters params may be forwarded to the base class if desired. This can be nested for deeper derived classes. The derived constructor must call EXACTLY ONE base constructor. The destructors are AUTOMATICALLY called in the REVERSE order that the constructors were called.
EDIT: There is an exception to this rule if you are inheriting from any virtual classes, typically to achieve multiple inheritance or diamond inheritance. Then you MUST explicitly call the base constructors of all virtual base classes and pass the parameters explicitly, otherwise it will only call their default constructors without any parameters. See: virtual inheritance - skipping constructors
You have to use initiailzers:
class DerivedClass : public BaseClass
{
public:
DerivedClass()
: BaseClass(<insert arguments here>)
{
}
};
This is also how you construct members of your class that don't have constructors (or that you want to initialize). Any members not mentioned will be default initialized. For example:
class DerivedClass : public BaseClass
{
public:
DerivedClass()
: BaseClass(<insert arguments here>)
, nc(<insert arguments here>)
//di will be default initialized.
{
}
private:
NeedsConstructor nc;
CanBeDefaultInit di;
};
The order the members are specified in is irrelevant (though the constructors must come first), but the order that they will be constructed in is in declaration order. So nc will always be constructed before di.
Regarding the alternative to super; you'd in most cases use use the base class either in the initialization list of the derived class, or using the Base::someData syntax when you are doing work elsewhere and the derived class redefines data members.
struct Base
{
Base(char* name) { }
virtual ~Base();
int d;
};
struct Derived : Base
{
Derived() : Base("someString") { }
int d;
void foo() { d = Base::d; }
};
Use the name of the base class in an initializer-list. The initializer-list appears after the constructor signature before the method body and can be used to initialize base classes and members.
class Base
{
public:
Base(char* name)
{
// ...
}
};
class Derived : Base
{
public:
Derived()
: Base("hello")
{
// ...
}
};
Or, a pattern used by some people is to define 'super' or 'base' yourself. Perhaps some of the people who favour this technique are Java developers who are moving to C++.
class Derived : Base
{
public:
typedef Base super;
Derived()
: super("hello")
{
// ...
}
};
There is no super() in C++. You have to call the Base Constructor explicitly by name.