C++: Creating class object as member of itself
by SlowCoder from LinuxQuestions.org on (#5MCFS)
Code:
Code:#include <iostream>
using namespace std;
class MyClass {
public:
MyClass *parent;
string value;
};
int main()
{
MyClass parentObj;
parentObj.value = "I am parent";
MyClass childObj;
childObj.value = "I am child";
childObj.parent = &parentObj; // use of & is the only way to not present an error. I'm probably getting this wrong.
cout << "child.value: " << childObj.value << endl; // "I am child"
cout << "parent.value: " << parentObj.value << endl; // "I am parent"
//cout << childObj.parent.value; // error: request for member 'value' in 'childObj.MyClass::parent', which is of pointer type 'MyClass*' ...
//MyClass p = childObj.parent; // error: conversion from 'MyClass*' to non-scalar type 'MyClass' requested
return 0;
}I'm new to C++, coming from C#, and probably haven't got my head wrapped around C pointers. I've written the above code to demonstrate my problem.
I want to be able to create an object that contains a reference to another object of same type, that is the "parent".
On many sites, the solution is to set the parent variable as a pointer, rather than an actual instantiation of a class. Ok. But none of them show how to reference the parent afterward.
I've commented a couple things I've attempted, and gotten errors.
I'd appreciate some help here.
Code:#include <iostream>
using namespace std;
class MyClass {
public:
MyClass *parent;
string value;
};
int main()
{
MyClass parentObj;
parentObj.value = "I am parent";
MyClass childObj;
childObj.value = "I am child";
childObj.parent = &parentObj; // use of & is the only way to not present an error. I'm probably getting this wrong.
cout << "child.value: " << childObj.value << endl; // "I am child"
cout << "parent.value: " << parentObj.value << endl; // "I am parent"
//cout << childObj.parent.value; // error: request for member 'value' in 'childObj.MyClass::parent', which is of pointer type 'MyClass*' ...
//MyClass p = childObj.parent; // error: conversion from 'MyClass*' to non-scalar type 'MyClass' requested
return 0;
}I'm new to C++, coming from C#, and probably haven't got my head wrapped around C pointers. I've written the above code to demonstrate my problem.
I want to be able to create an object that contains a reference to another object of same type, that is the "parent".
On many sites, the solution is to set the parent variable as a pointer, rather than an actual instantiation of a class. Ok. But none of them show how to reference the parent afterward.
I've commented a couple things I've attempted, and gotten errors.
I'd appreciate some help here.