Thank you both, Im starting to understand.
This was a general case, but my specific issue is that Class1 has a data member array of characters to store name. I cannot return an array, (which is what I need to do), so instead I said Class1 has also a pointer as a data member. So, upon instantiation of a Class1 object in the Class1 constructor, I initialize the pointer to the array.
Class1 therefore has the
Class1::getName() const;
function, which returns the pointer to the array. So if a Class2 function ever needs the name array, it can simply call the Class1::getName() member function from Class1, and it will have the name.
However, it doesnt work, unfortunately:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
class Class1 {
char name[41];
int health;
int strength;
char* Ptr;
public:
Class1(const char* str, const int hp, const int at);
virtual void setEmpty(); //virtual because setEmpty() is redefined in Class2
char* getName() const;
};
Class1::Class1(const char* str, const int hp, const int at) {
if (str && hp && at) {
strcpy(name, str);
health = hp;
strength = at;
*Ptr = name; //initially I had 'Ptr = name' before reading your comments (which didnt work, either)
//now though, it just underlines '=' in red and doesnt compile: 'a value of char* cannot be assigned to char'
}
else {
setEmpty();
}
}
char* Class1::getName() const {
return Ptr; //should it be return *Ptr; ?
}
|
If I try to run something like this, I get a read access violation:
1 2 3
|
void Class2::getName() const {
std::cout << "Name is: " << this->Class1::getName() << std::endl;
}
|
Why, if Class2 is derived from Class1?