user16188058
user16188058

Reputation:

About objects that are members of classes

I have the following code snippet:

class A{
    int i;
    public: A(int x): i(x) {}
    int get_i() { return i; }
};

class B{
    A a;
    int j;
public:
    B(int x, A y) { j = x; a = y; } // <--
    int get_j() { return j; }
};

Why do I get a compilation error on the line marked by <--? The compiler says that because A does not have a non-parameter constructor, but I would like to know exactly why the fact that A does not have a non-parameter constructor generates that error. Why is the error exactly on that line? I know how to change the code to work well, but I am preparing for an exam where we have to say which line produces the compilation error for a given piece of code. Thanks!

Upvotes: 1

Views: 58

Answers (2)

rawrex
rawrex

Reputation: 4064

A constructor runs its member initializer list before exectuing its body.

So, when the {j = x; a = y;} part of your constructor gets a chance to execute, the data member A a already should have been initialized using its default constructor. And then, inside the body of the constructor, you reassign new value to it, in the a = y statement.

You can (and in general should) use the solution proposed by @CoryKramer, using the member initializer list. But you may also benefit from knowing that introducing the default constructor (since the compiler won't synthesize one for you) to the A class can also be a valid option (depending on other factors).

class A{
    int i;
public: 
    A() = default;
    A(int x): i(x){}
    int get_i(){return i;}
};

Upvotes: 3

Cory Kramer
Cory Kramer

Reputation: 117856

A has no default constructor, just a parameterized constructor, so you'd need to construct B using the member initialization list syntax

class B{
    A a;
    int j;
public:
    B(int x, A y) : j(x), a(y) {}
    int get_j(){return j;}
};

Upvotes: 2

Related Questions