Reputation: 461
I am trying to access a variable inside derived class.
printf("%c", God.m_Please.me);
Inside God class declaration I have declared m_Please as
private:
Please *m_Please
and helpme is a variable declared in a class derived from Please
class Help : public Please
and me is defined as
unsigned char me[1000];
when I try to compile this I get error
error C2228: left of '.me' must have class/struct/union type
I am Using Visual Studio 6.0
Please reply back....
orward declare "class Please;" before God – wqking That helped to remove the first error :) but I still get 2 other errors
Thanks,
Upvotes: 1
Views: 1649
Reputation: 15165
Please* Please
is private. You cannot access a private member from a derived class. It must be protected.
class Please{
protected:
Please* m_Please;
int pplHelped;
};
class Help : public Please {
void whatever(){
//assume m_Please was initialized elsewhere
Please::m_Please->pplHelped; //do something with pplHelped
}
};
If you are trying to access the base member variable through an instance of the derived class, it should be declared public in the base class.
class Please{
public:
Please* m_Please; //init this somewhere
int pplHelped;
};
class Help : public Please{
};
void somefunc(){
Help God;
//assume m_Please was initialized in Constructor
printf("%d\n", God.m_Please->pplHelped;
}
Upvotes: 2
Reputation: 106904
You're syntax is confusing. A complete sample code would be appreciated.
If I understand you correctly, you are trying to access a private class member from a derived class. That won't work unless the derived class is declared as a friend to the base class. The proper way would be to use protected
instead of private
.
Oh, and as others suggested, use ->
instead of .
for accessing members of a pointer.
Upvotes: 0
Reputation: 106068
God.m_Please.me
is inreconcilable with PLease *m_Please
. As m_Please
is a pointer, use God.m_Please->me
. Still, that provides access to the character array, so you either need to specify which character in the array printf()
should display (e.g. me[0]
), or use the printf
format "%s"
which can display ASCIIZ strings.
Upvotes: 0
Reputation: 437336
m_Please
is a pointer (Please*
). You cannot use operator .
on pointers.
The correct way to do it would be
printf("%c",God.m_Please->me);
Upvotes: 1