Reputation: 153
I am a newbie to C++. I want to declare an object as a private member of another class. Is the instantiation of this object can be done with out the default constructor? A sample code is listed here:
class Vertex{
int i;
public:
Vertex(int j):i(j){};
Vertex(const Vertex & v){i=v.i;};
}
class Test{
Vertex v;
public:
Test(const Vertex & v1){v(v1);}
}
int main()
{//some code here;
Vertex v1(int j=1);
Test(v1); // *error: no matching function for call to 'Vertex::Vertex()'*
return 0;
}
It appears to me once declared an object as a private class member (e.g. Vertex v), the default constructor is immediately sought after. Anyway to avoid this? Thanks a lot.
Upvotes: 4
Views: 5634
Reputation: 546073
Vertex v1(int j=1);
This declares a function, v1
, which returns a Vertex
and takes an int
argument. What you want is
Vertex v1(1);
in addition, you need to use initialiser lists as the other answers have shown:
Test(const Vertex & v1) : v(v1) {}
Upvotes: 4
Reputation: 227578
Use the constructor initialization list:
Test(const Vertex & v1) : v(v1) {}
Once you're in the constructor's body (between the {
and }
), all data members have been initialized. If you don't do it explicitly, they get default initialized, which requires an available default constructor for user defined types.
Next, you are declaring a function here:
Vertex v1(int j=1);
What you probably meant is
Vertex v1(1);
Upvotes: 1
Reputation: 385385
Initialise Test::v
just as you initialised Vertex::i
. (It being private
is entirely irrelevant!)
So, using Test::Test
's member initialisation list:
Test(const Vertex & v1) : v(v1) {};
For consistency, then, I would also suggest:
Vertex(const Vertex & v) : i(v.i) {};
Initialise members wherever you can.
Upvotes: 2