C & C++/C++

[C++] Pure Virtual Function(순수 가상 함수), Abstract Class(추상 클래스)

  • -
728x90

Pure Virtual Function

순수 가상함수는 구현이 없는 가상함수를 의미한다.

class 클래스이름
{
public:
	virtual void 가상함수이름() = 0;
};

구현 대신 가상함수에 NULL(0)을 대입하면 해당 함수는 순수 가상함수가 된다. 이와 동시에 순수 가상함수를 포함하는 클래스는 추상클래스로 지정된다.

 

Abstract Class

추상 클래스가 되면 인스턴스를 만들 수 없다. 이 클래스로부터 다른 자식 클래스를 파생시켜 모든 순수 멤버 가상 함수를 오버라이드 한 뒤, 해당 자식 클래스부터 인스턴스를 다시 생성할 수 있다.

 

즉, 추상 클래스는 추상적인 형태만 제안하고, 실제 구현은 자식 클래스로 미루기 위해 사용된다.

class Person
{
public:
    void DoAction()
    {
        std::cout << "Good Morning!" << std::endl;
        Action();
        std::cout << "Sleep.." << std::endl;
    }
private:
    virtual void Action() = 0;
};

class Student : public Person
{
private:
    virtual void Action()
    {
        std::cout << "Study" << std::endl;
    }
};

class Employee : public Person
{
private:
    virtual void Action()
    {
        std::cout << "Work" << std::endl;
    }
};

int main(int argc, char** argv)
{
    Student student;
    Employee employee;

    student.DoAction();
    std::cout << std::endl;
    employee.DoAction();
}

Person은 Action이라는 순수 가상함수를 포함하는 추상클래스이다. 멤버 함수인 DoAction은 일어나서 Action을 하고 잠이든다는 의미이다. 어떤 Action을 할 것인가는 자식 클래스로 미뤄놓은 상태이다.

 

 

 

 

 

 

https://www.qaupot.com/posts/fcd45cddce874dbaac8a5345ca66f2d8

728x90
300x250
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.