acces base class member from derive class

G

gyan

Please go though following program:
#include <iostream.h>

class base {
public:
int basepublic;
protected:
int baseprotected;
};

class derived : public base {
public:
void compare(const derived *pb){
int a=pb->basepublic;
a=pb->baseprotected;
}
};

int main(){

return 0;
}

Now when i compile and run this program, it got all through.
MY question is how it is possible to access protected variable of a
different derive object in derive class's member function?
if i change argument of compare function from
const derived *pb to
const base *pb,
i get compilation error
" "1.cpp", line 14: Error: baseprotected is not accessible from
derived::compare(const base*)."
which is expected.
 
I

Ian Collins

gyan said:
Please go though following program:
#include <iostream.h>

class base {
public:
int basepublic;
protected:
int baseprotected;
};

class derived : public base {
public:
void compare(const derived *pb){
int a=pb->basepublic;
a=pb->baseprotected;
}
};

int main(){

return 0;
}

Now when i compile and run this program, it got all through.
MY question is how it is possible to access protected variable of a
different derive object in derive class's member function?

Because *pb is a derived and compare is a method of derived. Forget
base members and just consider derived ones, you would expect to be able
to see those, wouldn't you?
 
G

gyan

But Pb has been defined in main, outside the scope of derived class, so how
can we access protected member of pb object.member function of a class
should have access only to data member of its own object i.e. "this" and
not other object.
 
I

Ian Collins

gyan said:
But Pb has been defined in main, outside the scope of derived class, so how
can we access protected member of pb object.member function of a class
should have access only to data member of its own object i.e. "this" and
not other object.
Please quote context. I didn't realise you were replying to me.

In your example that you snipped, main was empty:

#include said:
class base {
public:
int basepublic;
protected:
int baseprotected;
};

class derived : public base {
public:
void compare(const derived *pb){
int a=pb->basepublic;
a=pb->baseprotected;
}
};

int main(){

return 0;
}

pb is a pointer to a derived, so any other instance of a derived can
fiddle with its private parts.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top