티스토리 뷰

[ Pure Virtual Functions ]

class Animal{
public:
   virtual void id() = 0;
};


- Function의 Body 생략.
- 이 Class를 상속받는 하위 Class는 이 Function을 사용할 때 Override를 해 주어야 한다.

[ Abstract Classes ]
- 하나 이상의 Pure Virtual Function을 가지는 Class.
- Base Class의 역할만 할 수 있다.
- 메인 Funcion에서 Object를 만들 수 없다.
- 상속받은 Class에서 Override(함수 재정의)를 하지 않으면, 그 Class도 Abstract Class이다.

[ 추상 클래스와 클래스의 상속, 가상 함수 사용 예제 ]

#include <string>
#include <iostream>

using namespace std;

class Pet{
   public:
   string name;
   virtual void print() const;
};

class Dog : public Pet{
   public:
   string breed;
   virtual void print() const;
};

int main()
{
   Pet vpet;
   Dog vdog;

   vpet.name = "I am a pet.";

   vdog.name = "I am a dog.";
   vdog.breed = "Great Dane"; 

   cout << vpet.name << endl;   // Output: I am a pet.

   vpet = vdog;
   // type 호환성때문에 assign은 가능.
   // vdog를 vpet에 넣지만, vpet의 크기에 맞게 잘라낸다고 생각하자.

   cout << vpet.name << endl;   // Output: I am a dog.

   (Called slicing problem)
   cout << vpet.breed;   // error C2039: 'breed' : is not a member of 'Pet'

   return 0;
}