Link to home
Start Free TrialLog in
Avatar of karana
karana

asked on

Simple , help me to get it ,

sir ,

My question is : Wat is the out put of the belowe  program ?



class P
{
Fucn(int s )
{
printf("%d" ,s);
}


class Q  (inherited from p)
{
 Func(int j)
{ printf("%d" ,j);
}
}


main(){
P x=new Q();
Q y=new Q();
P z=new Q();

x.Func(1) ;
 ((P)y).Func(1); // Type casting y to P
 z.Func(1);


}


Avatar of rstaveley
rstaveley
Flag of United Kingdom of Great Britain and Northern Ireland image

Well.... you need to make it compile first.

--------8<--------
#include <cstdio>
using namespace std;

class P
{
public:      void Func(int s )
      {
            printf("%d" ,s);
      }
};

class Q : public P
{

public:      void Func(int j)
      {
            printf("%d" ,j);
      }
};


main(){

      P* x=new Q();
      Q* y=new Q();
      P* z=new Q();

      x->Func(1) ;
      ((P*)y)->Func(1); // Type casting y to P*
      z->Func(1);

}
--------8<--------

Are you happy with this version?
....should be...

     int main()
     {
          // ....
      }

...too.
Avatar of baboo_
baboo_

uhm...

111

baboo_
Though you should note that the func method that gets called every time is Q::func, not P::func.  Ever.

Since all the objects are Q-type, at runtime, a method will call the lowest overridden version in the inheritance tree of the actual object.

(unless I'm mistaking Java and C++...  Hmm...  I'll look into it.  If anyone knows differently, please feel free to correct me)

baboo_
Not so, baboo_, because they are not virtual functions. Try it out (making the Funcs display differently of course)  and then try it out again with virtual functions.
Ah.  Indeed, rstaveley is correct.  Like I said, getting confused with Java.  Thanks.

...though the output is still 111 ;)
Avatar of karana

ASKER

it is a hypothetical programming language . it supports inheritance and dyanmic linking .
ASKER CERTIFIED SOLUTION
Avatar of rstaveley
rstaveley
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial