I want to call the constructor of a member m_foo
of Class A
in the constructor of Class A
. Is it nessecary to call it with m_foo = new Foo()
? Or can I call it without putting it on the Heap? I want to pass a pointer to an array of 256 Byte, so that the Foo object fills its member array with the data the pointer points to. But how would I call a contructor of a member variable that I declare in the headerfile?
A.hpp
class A{
public
A();
private:
Foo m_foo;
};
A.cpp
A::A()
{
//How to call constructor of class Foo here?
}
Foo.hpp
class Foo()
{
Foo(char* p)
{
memcpy(m_Array, p, sizeof(m_Array)/sizeof(m_Array[0]));
}
private:
char m_Array[256];
};
Use the member initialization list for the A
constructor :
A::A() : m_foo(...)
{
}
You can get the char*
required to build m_foo
from :
A
constructor :
A::A(char* p) : m_foo(p) {}
Or another function :
A::A() : m_foo(GetBuffer()) {}
If you don't mind passing the pointer to A's constructor, this may be what you want:
class A
{
public:
A(const char* p);
private:
Foo m_foo;
};
A::A(const char* p) : m_foo(p) // <- calls Foo's ctor here
{
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.