Reputation: 914
Consider following code:
---- A.h
class A{
private:
char* mStr;
public:
A(const char* str);
~A();
}
---- A.cpp
A::A(const char* str)
{
mStr = new char[MAX_SIZE];
strncpy(mStr,str,MAX_SIZE);
}
A::~A()
{
}
---- B.h
class B{
private:
A myA;
public:
B();
~B();
}
---- B.cpp
B::B()
{
myA = A("aaa");
}
B::~B()
{
}
Now the problem is that compiler is throwing error: error: no matching function for call to 'A::A()'
I want to avoid using pointer and want myA on stack if possible. If I pass argument during declaration in b.h, then also compiler throws error. What is the way to create an object like this?
Upvotes: 0
Views: 126
Reputation: 1361
class B{
private:
A myA;
public:
B();
~B();
}
In this class when you are using A myA
that means constructor will create one object of class A
. But in A myA
means it will call constructor A()
which is not defined.
As per my suggestion you can declare myA
as A* myA
and inside constructor B you can use new myA("aaa")
as below.
B::B(const char* str)
{
myA = new A("aaa");
}
Upvotes: 0
Reputation: 77304
One possible way would be using an initializer list:
B::B(const char* str) : myA("aaa")
{
}
In your example, the constructor of A does not take into account that memory needs to be allocated for it's private member, so it might crash if you don't fix that. But your problem should be solved with above syntax.
Upvotes: 1
Reputation: 9926
When you define a constructor taking certain arguments, you don't care how those are supplied or where they came from (well, for something simple like an int you don't). For an Example
Point::Point( int x, int y )
if the caller wishes to use values contained in another object or not it's up to him to get them and supply them - but this has absdolutely no bearing on how you write your constructor. So he would call the above constructor like:
Point apoint( 1, 2 );
// or: Point apoint( anObj.GetX(), and Obj.GetY() ); // or: Point apoint ( anObj.GetX(), anOtherObj.Y ); The syntax you have used with Lines constructor is for passing arguments to ether a member of that class or a base class of that class - in your case probably a member. To give you a nudge, here would be a good couple of constructors for your Line class, assuming your point class has a good set of constructors of its own - and if not, add them!
class Line
{
public:
Line( const Point& p1, const Point&p1 )
: m_Point1(p1), m_Point2(p2)
{}
Line( int x1, int y1, int x2, int y2)
: m_Point1(x1, yx), m_Point2(x2, y2)
{}
private:
Point m_Point1;
Point m_Point2;
};
Called like:
Point aPoint, bPoint;
.
.
Line aline( aPoint, bPoint );
Line bline( 1, 1, 2, 2 );
Upvotes: 1