Hi guys, I am bit puzzled with a requirement on my program:
Say I have a class A with some private variables

class A
{
 private:
 string variabe;
};

Then I have class b with some other private variables

class B
{
    string varialb1;
 };

Now I have a class C with a pointer type class C that should be initialized in the constructor by using object of class A. So

class C
 {
   private:
   A a;
  };

  C *pointer = &a; //this does not work

So how can I initiliaze *c with object of A?

Thank you.

Recommended Answers

All 2 Replies

Your question makes no sense. The C object already contains an object of type A. The object of type A gets created when the C object is created.

Your code also makes no sense. a is an object of type A, so you cannot make a pointer-to-C point at it. It makes no sense. It's like trying to make a char-pointer point at a float.

This makes as much sense as your code above:

float x;
char* pointerToX = &x; // cannot make a char* point at a float

Your syntax on line 7 is never going to work, it could only ever work is C was an acester of A.

But you can initialise a class in its constructor from another class like this

class C
{
public:
  explicit C(const A& inita) : a (inita)
  {
  }

private:
  A a;
};

C *pointer = new C(a);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.