I have the following code:
class A{
public:
A(int* i){
std::cout << "in A()" << i << std::endl;
}
};
class B: public A{
public:
B(): i{new int{10}}, A{i}{
std::cout << "in B()" << std::endl;
}
private:
int* i;
};
int main()
{
B b;
}
In A
constructor I have 0 (which is expected). But I want to initialize i
before. Is it possible at all?
The safest approach is to initialise every variable at the point of construction. For class members, your constructors should ensure that every variable is initialised or that it has a default constructor of its own that does the same.
Default constructors are one of the special member functions. If no constructors are declared in a class, the compiler provides an implicit inline default constructor. If you rely on an implicit default constructor, be sure to initialize members in the class definition, as shown in the previous example.
We have to call constructor from another constructor. It is also known as constructor chaining. When we have to call same class constructor from another constructor then we use this keyword. In addition, when we have to call base class constructor from derived class then we use base keyword.
The base class members are already initialized by the time your derived-class constructor gets to run. You can assign them, if you have access, or call setters for them, or you can supply values for them to the base class constructor, if there is one suitable.
i
is a data member of class B
, so in order to be created, an object of class B
has to be created first. So the answer, is no.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With