Initialize class in another class



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
class A{
   public:
      A(const char *name) {
           std::cout<<name;
      }
};
class B{
   public:
      A objA;
      B();
};
B::B():objA("objectA")
{
  /// here
}
int main() {
  B objB;
}


The above code is correct for initialize class in another class (I initialize objA("objectA") when defination constructor B)
But I want to initialize objA in constructor B ( ///here )
How to do that? (objA not a pointer )
Challenge : if I declare array : A objA[5];
How to initialize with names is : "objectA1","objectA2","objectA3","objectA4","objectA5",
Thank all.
Last edited on
1
2
3
4
5
B::B()
 : objA( "objectA" )
{
  /// here
}

The above code is correct for initialize class in another class (I initialize objA("objectA") when defination constructor B)
But I want to initialize objA in constructor B ( ///here )

You can't initialize any member ///here, because all members are initialized before ///here starts.

You can only modify (already initialized) members ///here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

class A{
   public:
      A(const char *name) {
           std::cout<<name;
      }
};

class B{
   public:
      A objA[3];
      B();
};

B::B()
: objA {"foo", "bar", "gaz"}
{
  /// here
}

int main() {
  B objB;
}
Dear @keskiverto
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

class A{
   public:
      A(const char *name) {
           std::cout<<name;
      }
};

class B{
   public:
      A *objA[3];
      B();
};

B::B()
{
  for(int i=0;i<3;i++) {
      char name[10];
      sprintf(name,"objA%d",i);
      objA[i] = new A(name);
  }
}

int main() {
  B objB;
}

I dont know when use " A * objA[3] " or " A objA[3] "
Do you explain when to use each case? ( strengths/weaknesses )
Thank @keskiverto
A* objA[3] is for when you want an array of pointers to objects of type A.

A objA[3] is for when you want an array of actual objects of type A.

In your latest code, you need to store the pointers, because that's how you access the memory on the heap that you're dynamically allocating.
Last edited on
I know that : I need " delete objA[i] ;" in B::~B() .Is that enough ? . I hear that, If use pointer , you must Pointers Management and Memory Management . But I just know delete object in destructor .
If you can avoid pointers and dynamic allocations the code often becomes simpler, with less chance of making mistakes. Personally, I wouldn't use pointers and dynamic allocations unless there is a reason for it.
Thank @Peter87
Topic archived. No new replies allowed.