Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize member before base constructor. Possible? [duplicate]

Tags:

c++

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?

like image 511
nikitablack Avatar asked Jun 19 '15 15:06

nikitablack


People also ask

Should a constructor initialize all members?

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.

Does default constructor initialize members?

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.

How do you initialize a base class constructor from a derived class?

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.

Can derived class initialize base member?

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.


1 Answers

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.

like image 104
gsamaras Avatar answered Sep 28 '22 02:09

gsamaras