Comming from Java, I have difficulty with the code below.
In my understanding b is just declared on line 3 but not instantiated.
What would be the text book way of creating an instance of B in class A?
class A {
private:
B b;
public:
A() {
//instantiate b here?
}
};
Edit: What if B does not have a default constructor?
You could explicitly initialize b in A's constructor's initialization list, for example
class A {
B b; // private
public:
A : b() {} // the compiler provides the equivalent of this if you don't
};
However, b would get instantiated automatically anyway. The above makes sense if you need to build a B with a non-default constructor, or if B cannot be default initialized:
class A {
B b; // private
public:
A : b(someParam) {}
};
It may be impossible to correctly initialize in the constructor's initialization list, in which case an assignment can be done in the body of the constructor:
class A {
B b; // private
public:
A {
b = somethingComplicated...; // assigns new value to default constructed B.
}
};
You have created an instance of b in line 3. This line is enough so that B's constructor is called. If you have code like this
class A {
private:
B *b;
public:
A() {
//instantiate b here?
}
};
then it would make sense to instantiate b in A's constructor like
A()
{
b = new B();
}
The correct phase your looking for is "C++ initialization list". This initialization list is called/initialized before the constructor is called
In case of Default constructor, compiler equvalient constructor will be A() : B() {}
A very good reference
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
At line 3, it is simply a declaration of B. However somewhere in your code where you have:
A a;
or
A a();
This calls the constructor of A. The internal b private member is full or garbage, as in not initialized. You are correct in that you can and probably should initialize member variable during construction where possible. There are two ways to do this:
A ()
{
b = B ();
}
Like you said:
or
A () : b (B())
{
}
The second version (initialization list) is slightly more efficient since it creates the new B object directly inside b. Whereas the first version creates a temporary and then moves that into b. This is the case when you initialize members from passed in parameters anyway (for non built in types). I'm making an assumption its the same in this case, but someone will be able to clarify.
Related
This is a question about constructors. Two C++ classes A and B are related conceptually as
class A
{
B b;
};
class B
{
A *a;
};
The question is, when an instance of A is created, I want its member B to be constructed with a pointer to A. So it seems B requires a constructor that has a pointer to an instance of A as an argument, and that that constructor of B be invoked when an instance of A is constructed, rather than the default constructor of B.
Is there a simple way to do this?
Using struct here just for the public defaults.
struct A;
struct B {
B(A *a_ptr = 0) : a(a_ptr) {}
A *a;
};
struct A {
A() : b(this) {}
B b;
};
You might get a warning in the constructor for A from a busybody compiler that this points to an object that has not been fully constructed.
I have a user defined class, say A. I have another user defined class B which publicly extends A.
When I define the constructor of B, I have to call the constructor of A in the member initializer list of B's constructor, or else the compiler will call the default constructor.
class A {
int a;
public:
A(int x = 0) {
a = x;
}
};
class B : public A {
int b;
public:
B(int x = 0) : A(2*x) {
b = x;
}
};
Now, I understand the logic behind all this. However, what I want to know is what happens when I do this instead:
class A {
int a;
public:
A(int x = 0) {
a = x;
}
};
class B : public A {
int b;
public:
B(int x = 0) {
A(2*x);
b = x;
}
};
I mean, we all know that the compiler will call the default constructor of A before it enters the body of the B's constructor. Now, the first line of B's constructor body is to call another constructor of A (which takes arguments). So, what does this result in? Two different constructors of the superclass are getting called here whenever an object of the subclass is being created. Please explain what happens...whether two objects will be created or what.
That doesn't call the constructor for the A subobject of the B being initialised. Instead, it creates and destroys a temporary object of type A. The only way to call the constructor of the base subobject is through the initialiser list, as in the first example.
Now, the first line of B's constructor body is to call another constructor of A (which takes arguments). So, what does this result in?
It constructs a temporary A and the temporary object is discarded right away. That call has no relationship to initializing the A part of B.
Is there some way to initialize(?) member variable c of type C in the first part of the below example? Or must I use the new() method shown in the second part of the example?
Class B takes class A as an injected dependency. So does class C. Class B is additionally composed of class C.
How do I get the injected A to B's member C?
Part 1
class A { // ...; };
class C {
public:
C(A &a) : a(a) {} // constructor
};
// Does not work as is. Want to make compiler manage C lifetime.
class B {
public:
B(A &a); // constructor
C c(a); // member variable
};
// constructor
B::B(A &a) : a(a) {
}
Part 2
// Works, but requires programmer to manage C's lifetime.
class B {
public:
B(A &a); // constructor
C *c; // member variable
};
// constructor
B::B(A &a) : a(a) {
c = new C(a);
}
Several good answers below! My apologies for the confusing example. I have up-voted all of the good answers and questions. Unfortunately I can only mark one answer as the accepted answer, so I am choosing the first one which gave me the "ah-ha" moment in which I saw the solution to my real problem, which was more complex than my lame example here.
Member variables are initialized in constructor's initialization list (before body) so you need to do that:
B::B(A &a)
: c(a) // Calls constructor C(a) on member c
{}
You almost have it:
class B {
public:
B(A &a);
C c(a); //see note 1
};
B::B(A &a) : a(a) { //see note 2
}
Note 1:
There are two problems with C c(a); here:
a is not in scope. a only exists within the scope of the constructor, so c needs to be initialized from there.
Until C++11, non-static data member initializers (NSDMIs) were prohibited. Even in C++11, though, you must use an equals sign (C c = value;) or braces (C c{value};) when initializing an NSDMI.
Note 2:
You've almost got this right:
B::B(A &a) : a(a)
You're trying to initialize a data member called a with the argument given to the constructor. You actually want to initialize c like this, not a non-existent a:
B::B(A &a) : c(a)
The lifetime of c will be that of the instance of the B class. Using dynamic memory management is certainly not necessary.
"How do I get the injected A to B's member C?"
You can do so using B's constructor member initializer list
class B {
public:
B(A &a) : c(a) {
// ^^^^
}
C c; // <<< It's not possible to initialize members in their
// declaration.
};
The following:
C(A &a) : a(a) {}
will not compile since a (the first a in the initialization list) is not a member variable of C.
Same applies to the constructor of B.
I'm not used to c++ and I'm having a problem writing a constructor.
See this example, is a short version of the code I'm working on:
class B {
public:
B(int x);
}
class A {
public:
B b;
A(){
// here I have to initialize b
}
}
That throws a compiler error since I need to initialize b in A's constructor because B does not have a default constructor.
I think I have do it in the initialization list, but the B(int x) argument is a value I have to calculate with some algorithm, so I don't know how this should be properly done, or if I'm missing something or doing it wrong.
In other language like java I would have a reference to B and initialize it inside the A's constructor after the other code I need to get the value for the initialization.
What would be the right way to initialize b in this case?
Thanks!
You can invoke functions in your constructor initializer list
class B {
public:
B(int x);
}; // note semicolon
class A {
public:
B b;
A()
:b(calculateValue()) {
// here I have to initialize b
}
static int calculateValue() {
/* ... */
}
}; // note semicolon
Note that in the initializer list, the class is considered completely defined, so you can see members declared later on too. Also better not use non-static functions in the constructor initializer list, since not all members have yet been initialized at that point. A static member function call is fine.
You use an initializer list, something like this:
A() : b(f(x)) {}
#include<iostream>
class B {
public:
B(){} // A default constructor is a must, if you have other variations of constructor
B(int x){}
}; // class body ends with a semicolon
class A {
private:
B b;
public:
A(){
// here I have to initialize b
}
void write(){
std::cout<<"Awesome";
}
};
int main(){
A a;
a.write();
}
In C++, if you have a constructor that takes an argument, a default constructor is a must, unlike other languages as Java. That's all you need to change. Thanks.
Newbie here. I am looking at company code.
It appears that there are NO member variables in class A yet in A's constructor it initializes an object B even though class A does not contain any member variable of type B (or any member variable at all!).
I guess I don't understand it enough to even ask a question...so what's going on here!? My intuition is that you need a variable before you even try to initialize it. How is it possible (or what good does it do) to initialize an object without having the object?
.h:
class A: public B
{
public:
A(bool r = true);
virtual ~A;
private:
}
.cpp:
A::A(bool r) : B(r ? B::someEnumeration : B::anotherEnumeration)
{
}
A::~A()
{
}
Please help.
Thanks,
jbu
Class A (publicly) inherits from class B:
class A: public B
The only way to initialize a base class with parameters is through the initializer list.
This is actually the only way to call the ctor of a base class in C++ as there is noch such thing as super().
class A : public B
{
};
class B
{
public:
int x;
};
A is a derived type from B. Or A inherits B.
So this is valid...
A a;
a.x = 3;
The rest of your code is just calling B's constructor when A is constructed.
class A: public B
{
public:
A(bool r = true); // defaults parameter 1 as "true" if no arguments provided ex A *pA = new A();
virtual ~A;
private:
}
.cpp
A::A(bool r) : B(r ? B::someEnumeration : B::anotherEnumeration)
{
// calls parent class, and initialize argument 1 with some enumeration based on whether r is true or false
}
A::~A()
{
}
Since construtor cannot be inherited so base class data members are to be initialized by passying argument in derived class constructor and with the help of initialization list.
You should also know that in case of polymorphic class initialization of vptr to respective virtual table is done only in constructor.