-1

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];
};
tzippy
  • 6,458
  • 30
  • 82
  • 151

2 Answers2

6

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()) {}
quantdev
  • 23,517
  • 5
  • 55
  • 88
  • Don't use that ; after though EDIT: I see you fixed it. I upvoted this answer. – AlexanderBrevig Aug 26 '14 at 12:46
  • Eh, I didn't know about that...is that standard C++? Or only C++11? – ATaylor Aug 26 '14 at 12:48
  • And how would I pass a byte array to `m_foo`? Since it accepts a pointer I should pass the first element of an array, but how? I want to initialize `m_foo` with a byte array of 256 bytes. – tzippy Aug 26 '14 at 12:48
  • @tzippy depends what you do : you can pass the `char* p` to the `A` ctor : `A::A(const char* p) : m_foo(p)`, or allocate it in `m_foo(...)` or even call another function `: m_foo(getbuffer())` . Hope this helps. – quantdev Aug 26 '14 at 12:52
  • 7
    @ATaylor what book did you learn from that didn't cover this? I don't think it was present in TC++PL 1 (1985) but surely it was around by TC++PL 2 (1991) – M.M Aug 26 '14 at 12:52
  • 1
    @MattMcNabb None. Most of the things I know about C++, I know from my (just about adequate) job training in C and C#. The only thing they told us about C++ was: 'It has classes' and 'It has new'. The rest is self-taught. And the reference I looked at stated something about C++11, that's why I asked. – ATaylor Aug 26 '14 at 13:38
  • @ATaylor `new` is something you should rarely use , so that's an unfortunate synopsis of the language. *Accelerated C++* is very good if you already know how to program , although unfortunately it doesn't seem to be updated for C++11. [Book list](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – M.M Aug 26 '14 at 13:42
2

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
{
}
fscibe
  • 61
  • 5