Pure Virtual Functions and Abstract Classes in C++

来源:互联网 发布:人体透视镜软件下载 编辑:程序博客网 时间:2024/05/22 05:05

reference http://quiz.geeksforgeeks.org/pure-virtual-functions-and-abstract-classes/

1) A class is abstract if it has at least one pure virtual function.

2) We can have pointers and references of abstract class type.

 

3) If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.

4) An abstract class can have constructors.
For example, the following program compiles and runs fine.

#include<iostream>
using namespace std;
 
// An abstract class with constructor
class Base
{
protected:
   int x;
public:
  virtual void fun() = 0;
  Base(int i) { x = i; }
};
 
class Derived:public Base
{
    int y;
public:
    Derived(int i,int j):Base(i) { y = j; }
    void fun() { cout << "x = " << x << ", y = " << y; }
};
 
int main(void)
{
    Derived d(4, 5);
    d.fun();
    return 0;
}
 
Interface vs Abstract Classes:
An interface does not have implementation of any of its methods, it can be considered as a collection of method declarations. In C++, an interface can be simulated by making all methods as pure virtual.
0 0
原创粉丝点击