In the below program i have used two classes , and i am trying to relate the with aggregation, i have declare class A as private in class B, and with the help of constructor i am initizing base address of class A object to private member of class B object that is (A object). i am trying to pass the class A values to class B usng parametrized constructor, but i am getting garbage values like,
#include <iostream>
using namespace std;
void create (B * &obj2, int siz)
{
std::cout << obj2[0].get_nn (); //this will run fine
for (int i = 0; i < siz; i++)
obj2[i] = B (10, "pranjal"); //this will also run fine
std::cout << obj2[0].get_nn ();
}
// same line printing again, this will not give output
// ***************************************
void display ()
{
std::cout << object.get_data () << object.get_stringdata ();
}
// giving garbage values
// why is it happening
// *********************************program
// ************************************** enter code here
// Online C++ compiler to run C++ program online
class A {
int rool;
string name;
public:
A () { };
A (int a, string name);
int get_data () {
return rool;
}
string get_stringdata () {
return this->name;
}
};
A::A (int a, string name)
{
this->rool = a;
this->name = name;
}
void getdetails (A * obj)
{
for (int i = 0; i < 3; i++)
obj[i] = A (20, "pranjal");
}
class B {
int bbb;
string name;
A object;
public:
B () {};
B (A s) {
object = s;
}
string get_nn () {
return object.get_stringdata ();
}
B (int a, string b);
void display () {
std::cout << object.get_data () << object.get_stringdata ();
}
};
void dis (B * obj2)
{
for (int i = 0; i < 2; i++) {
obj2[i].display ();
}
}
void create (B * &obj2, int siz)
{
std::cout << obj2[0].get_nn ();
for (int i = 0; i < siz; i++)
obj2[i] = B (10, "pranjal");
std::cout << obj2[0].get_nn () << "sd";
}
B::B (int a, string b)
{
bbb = a;
name = b;
}
int main ()
{
A *obj = new A[3];
getdetails (obj);
B *obj2 = new B[3];
for (int i = 0; i < 3; i++) {
obj2[i] = B (obj[i]);
}
create (obj2, 3);
dis (obj2);
obj2->display ();
return 0;
}