So what I am trying to do, I have two classes named ClassA and ClassB, in ClassB there exists a pointer which is referring to an array of ClassA objects. But when I am trying to save the objects inside the array the details are not getting reflected. I tried debugging the same and it's giving me segmentation fault. Is there anything I am doing wrong?
Classes File:
#include <bits/stdc++.h>
using namespace std;
class ClassA{
private:
string name;
string phone;
public:
ClassA(string name, string phone)
{
this->name = name;
this->phone = phone;
}
string getName()
{
return name;
}
string getPhone()
{
return phone;
}
};
class ClassB{
private:
ClassA* details;
int size;
public:
ClassB()
{
size = 0;
details = (ClassA*)malloc(5*sizeof(ClassA));
}
void addDetails(string name, string phone)
{
ClassA* temp = new ClassA(name, phone);
details[size++] = *temp;
// cout<<details[size-1].getName()<<" "<<details[size-1].getPhone()<<endl;
}
void print()
{
for(int i = 0; i < size; i++)
{
cout << details[i].getName() << " " << details[i].getPhone() << endl;
}
}
};
Driver Code:
#include "temp.h"
using namespace std;
int main()
{
ClassB b;
b.addDetails("A", "123");
b.addDetails("B", "456");
b.addDetails("C", "789");
b.print();
return 0;
}
Anyone, please help me out on this.