is this behaviour acceptible?

B

bala

hey, i found something confusing. Look at the following code:

#include <iostream>

class mybase{
protected:
virtual void printX(){
std::cout << "i am from the base X" << std :: endl;
}
};

class firstsub : public mybase{
public:
void printX(){
std::cout << "i am from first sub class X " << std :: endl;
}
};

class secondsub : public firstsub{
private:
void printX(){
std::cout << "i am from second sub class X " << std ::
endl;
}
};

int main(){
firstsub ofs;
firstsub* pfs;
secondsub oss;

pfs = &ofs;

pfs -> printX();

pfs = &oss;

pfs -> printX();
}


And the output is:

[bhaskar@dallas basics]$ g++ inherit4.cxx

[bhaskar@dallas basics]$ ./a.out

i am from first sub class X
i am from second sub class X



I am bit confused to see the second message in the output...

Any clarifications?
--Bala
 
K

Karl Heinz Buchegger

bala said:
i am from first sub class X
i am from second sub class X

I am bit confused to see the second message in the output...

Any clarifications?

Thats the normal behaviour of virtual functions.
At runtime, the actual type of the object the pointer points
to is looked up and the function for that object is selected.

Why are you confused, what did you expect?
 
B

bala

sorry for not mentioning this before.

the confusion is not about late binding, but about access.

you can see that the method is private in the second sub class.
 
L

lilburne

bala said:
sorry for not mentioning this before.

the confusion is not about late binding, but about access.

you can see that the method is private in the second sub class.

So? It is public in interface of the object that you call it from.
 
R

roberth+news

| yes,
|
| what i want to know is :
|
| Is everything OK here?

Yes. A quote from the standard:

11.6 Access to virtual functions [class.access.virt]

1 The access rules (clause 11) for a virtual function are determined by
its declaration and are not affected by the rules for a function that
later overrides it.

[Example:
class B {
public:
virtual int f();
};
class D : public B {
private:
int f();
};
void f()
{
D d;
B* pb = &d;
D* pd = &d;
pb->f(); //OK: B::f() is public,
// D::f() is invoked
pd->f(); //error: D::f() is private
}
end example]

Access is checked at the call point using the type of the expression
used to denote the object for which the member function is called
(B* in the example above). The access of the member function in the
class in which it was defined (D in the example above) is in general
not known.
 

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,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top