Interaction of classes

if I have two classes One and Two(which has an attribute called 'number'),can I (if its possible,then how) make a dynamically allocated set of 'number' pointers, who point on a object of type One, using a constructor of class Two?
which type should this set be?

(the interface of class One is not important)

what I'm trying to do is something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class One{
};

class Two{
    int number;
    One *set; // should this set be type One ?

    public:
    Two(){ 
     *set = new One[number];
    }
    
     ~Two(){
     delete set;
     }
    };
Your code is fine, you just need to initialize 'number' before line 10
And use delete[] on line 14.
You may want to overload the copy constructor and assignment operator to avoid errors
Last edited on
well i managed to make the set, i initialized 'number' and corrected line 14.. but, what if class One has an attribute called 'name' of type string..now,the first element of 'set' is an object of type One..how can i write a string in his 'name' attribute ? how can i change the values of all the 'name' attributes of all the objects pointed on by 'set' pointers? how should a function doing this look like?
Last edited on
how can i write a string in his 'name' attribute ?
set[0].name = "First 'One' object name";
how can i change the values of all the 'name' attributes of all the objects pointed on by 'set' pointers?
1
2
for ( int i = 0; i<number; i++ )
    set[i].name = "All will have this name";
you misunderstood me,but in the end i figured it out.i wanted a function which has two arguments for example, index number of an element in 'set' and a string, which can access objects pointed on by pointers in 'set' ..and in the end i got this:
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <conio.h>


using namespace std;

class One{
      string name;
      public:
      void SetName(string name){ 
           this->name=name; 
           }

   };
      
class Two{
      int number;
      One *set;
      
      public:
      Two(){
            number=5;
            set = new One[number]; 
            }
      
      void Function(int index,string name){
           set[index-1].SetName(name);
           }
           
      ~Two(){ delete[] set; }
      
      };

int main(){
    
    One test;
    Two dummy;
    dummy.Function(1,"Obama");


    getch();
    return 0;
}



thnx very much ;)
Last edited on
Topic archived. No new replies allowed.