Reputation: 14670
I have two classes L1 and L2 and the definition of L2 includes L1 as a member object. Each of L1 and L2 has its own constructor. Obviously, when instantiating L2, its constructor must call L1's constructor. However, I don't know how to go about doing this. Here is a (failed) attempt along with the accompanying compiler error.
class L1
{
public:
L1(int n)
{ arr1 = new int[n] ;
arr2 = new int[n]; }
private:
int* arr1 ;
int* arr2 ;
};
class L2
{
public:
L2(int m)
{ in = L1(m) ;
out = L1(m) ; }
private:
L1 in ;
L1 out;
};
int main(int argc, char *argv[])
{
L2 myL2(5) ;
return 0;
}
The compilation error was:
[~/Desktop]$ g++ -g -Wall test.cpp (07-23 10:34)
test.cpp: In constructor ‘L2::L2(int)’:
test.cpp:21:5: error: no matching function for call to ‘L1::L1()’
test.cpp:8:3: note: candidates are: L1::L1(int)
test.cpp:6:1: note: L1::L1(const L1&)
test.cpp:21:5: error: no matching function for call to ‘L1::L1()’
test.cpp:8:3: note: candidates are: L1::L1(int)
test.cpp:6:1: note: L1::L1(const L1&)
How do I go about fixing this code?
Upvotes: 2
Views: 196
Reputation: 477494
Use constructor-initializer lists, e.g.:
L2(int m) : in(m), out(m) { }
Never use assignment when you should be using initialization.
Upvotes: 2
Reputation: 24846
Use initialization list:
class L2
{
public:
L2(int m) : in(m), out(m) //add this
{
}
private:
L1 in ;
L1 out;
};
Upvotes: 7