0

I just started learning C++
let's say i have 2 classes classes A and B

Class A = a1(a,b)

I want an instance of class B attributes to be like this where a1 is an instance of class A:
Class B = b1(x,y,a1,z)

how do i go about doing this?
does anyone has any examples for me?

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by sfuo
0

This is one of the most basic examples I can come up with that includes exactly what you asked.

#include <iostream>
using namespace std;

class ClassA
{
	int a, b;

	public:
	ClassA(){}; //need a default constructor
	ClassA(int _a, int _b)
	{
		a = _a;
		b = _b;
	}
};

class ClassB
{
	int x, y, z;
	ClassA a1;

	public:
	ClassB(){}; //not needed in this but should have one
	ClassB(int _x, int _y, ClassA _a1, int _z)
	{
		x = _x;
		y = _y;
		a1 = _a1;
		z = _z;
	}
};

int main()
{
	ClassA A(1, 2);
	ClassB B(4, 5, A, 6);


	return 0;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.