how do I create a subclass?

Suppose I have structure A;

1
2
3
struct A {
  int Aint;
} InstanceOfA;


Now I want to create a new structure called B:

1
2
3
struct B {
  int Bint;
};


Such that InstanceOfA always automatically creates an instance of B and both have access to their integer members (at least public ones). Is this possible?

I am effectively asking that A and B are the same class, but with declarations in different locations (such that functions requiring members of A need not explicitely include headers for B, and vice versa)
Last edited on
Make B inherit from A. I believe that's what you are wanting.
I'm not sure. A base class doesn't "know" anything about its inherited class... Take this example:

1
2
3
4
5
6
7
struct B : public A { // ERROR
  int Bint;
};

struct A : public B{
  int Aint;
};


I was thinking of maybe doing this:

1
2
3
4
5
6
7
8
9
10
11
12
13
struct B {
  B(A*);
  A* PointerToA;
  int Bint;
};

B::B(A* pA) {
  PointerToA = pA;
}

struct A : public B(this){ // can I do this??
  int Aint;
};


That way struct B will always have access to struct A by inheritance, and struct B can access struct A through the pointer. But can I pass a this pointer like that??
you want class B member variable to be accessed by class A . and A member variable to be accessed by B . Right ?
cannot you make B class friend of A .
you can do this:
1
2
3
4
5
6
7
8
9
struct A
{
A()
: b_(this)
{
}
private:
B b_;
}


This way an instance of b is created with an instance of a and b is aware of a.
But you will need to forward declare A before B like this:
1
2
3
class A;
class B{...};
class A{...};
Topic archived. No new replies allowed.