Virtual method and base-type pointer make polymorphism in C++

The core of object-oriented programming may be inheritance and polymorphism. C++ uses virtual method and base-type pointer to achieve this, which is different from Java. In Java, everything is object, and there is no concept of pointer (actually, we can treat the object handlers as "safe pointers"). Java uses some easily confusing mechanisms to achieve polymorphism, as we discussed before. However, in C++, there are not only pointers to objects, but also object variables, which allows programmer to operate on an object directly. Let's see the code below.

#include  < iostream >
using   namespace  std;

class  A
{
public:
    
void print(){ cout<<"A.print()"<<endl; }
}
;

class  B :  public  A
{
public:
    
void print(){ cout<<"B.print()"<<endl; }
}
;

void  print(A a) { a.print(); }
void  print(A *  a) { a->print(); }

main()
{
    A a, 
*pa, *pb;
    B b;
    pa 
= &a;
    pb 
= &b;
    a.print();
    b.print();
    pa
->print();
    pb
->print();
    print(a);
    print(b);
    print(pa);
    print(pb);
}

Compile and run it, we find no polymorphism. It prints:

A.print()

B.print()

A.print()

A.print()

A.print()

A.print()

A.print()

A.print()

If we add keyword "virtual" to the head of print() in class A like this:

class  A
{
public:
    
virtual void print(){ cout<<"A.print()"<<endl; }
}
;

It prints:

A.print()

B.print()

A.print()

B.print()

A.print()

A.print()

A.print()

B.print()

Look, print() called by pointers of type A all print the right thing according to polymorphism. But still, print() called by variables directly doesn't print the thing defined in subclass. So we come to the conclusion: C++ uses virtual method and base-type pointers to realize the polymorphism mechanism.

Additionally, virtual can be inherited through the whole hierarchy. We can add a class C in the program like this:

class  C :  public  B
{
    
public:
        
void print() { cout<<"C.print()"<<endl; }
}

and add a variable of C and a pointer of type A referencing to this variable, as well as the print statements:

* pc;
C c;
pc 
=   & c;

c.print();
print(c);
print(pc);

It will do the similar thing.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值