Need some aclaration about instancing classes whithin a class

I have :
Class A h an cpp
Class B h and cpp

I want to create a B instance into A.

I think I understand how to do it, but I have some questions.

I can declare private or public access for B, isn't it ?

1.- If I want to create the instance always I have to put the code at the beginning of tha class code , isn't it ?

2.- But if I wanted to create it into a method ? How must I to refer to the class :
ClassB classA::the_classb_to_create ???

In both casses, 1 and 2, must I to delete the instance into destructor?

If I create a private instance into a function, it is automatically destroyed at the end of function ?

Thanks


Last edited on
The answers are as follows :
There is no need to inherent B to A class.
just write

#include "B.h"
1
2
3
4
5
6
7
8
9
class A
{
   private:
              ....... 
           .....
   public : 
          B b ; 
             ........
};



in class A .h thats all you have to do
2) you have to have desturctor in both the class A an B .
No .. you have to have the destructor for both the class .. this is good progrmamming .
}
Thanks bluecoder.


As you wrote, simply writting 'B b' meaning I'm going to have the b instance? There, I only declare public access for b, isn't it ? So, I have to create the intance at the beginning of A.cpp, just before the constructor?

And 'But if I wanted to create it into a method ? ' is still on the air...


@If I create a private instance into a function, it is automatically destroyed at the end of function ?

All variables (primitive or class) that are created in a function will run their destructor (all members of the class will run their destructor) when reaching the end of the function or at return. For example a int created in a function (pushed on stack) only have the scope within that function meaning it can only be used inside that function. As the program goes out of scope, all variables will be deleted (pop the stack).

However if you used "new" the variable will be allocated on the heap and thus need to be deleted with "delete" before the function goes out of scope. "new" is mostly used in the constructor of a class, or should always if possible. This means that a delete command needs to bee run in the destructor of class to avoid memory leak. If you know the rule of three, you will know that doing something special in the destructor probably mean that you have to do something similar in your assignment-operator and copy-constructor as these function are created for you by default. Meaning that if you use "new" in your constructor you probably need use "delete" and "new" when copying or assigning the class.

Their are some exceptions tho such as throwing exceptions and thread changes. This situations need special attention.

Topic archived. No new replies allowed.