nakka soft world !

상속의 개념 본문

프로그래밍언어/C++

상속의 개념

nakka 2017. 3. 25. 00:10
728x90

상속(inheritance)의 개념


객체지향 프로그래밍의 3가지 특징은 "캡슐화(encapsulation)", "상속성(inheritance)", "다형성(polymorphism)"입니다.

// Base, Super

class People

{

string name;

int age;

};

// Derived, Sub class

class Student : public People   // 상속(inheritance)

{

int id;

};

class Professor : public People

{

     int major;

};

int main()

{

}


class Base

{

private:

int a; // 자신의 멤버 함수와 friend함수만 접근


protected:

int b; // 자신의 멤버 함수와 friend함수만 접근

      // 파생클래스의 멤버 함수와 friend함수만 접근


public:

int c;

};


class Derived : public Base

{

public:

void foo()

{

a = 10; // error

b = 10; // OK

c = 10; // ok

}

};


int main()

{

Base base;

base.a = 10; // error

base.b = 10; // error

base.c = 10; // OK

}



상속과 생성자 소멸자 (inheritane & constructor)

class Base

{

public:

Base() { cout << "Base()" << enld; }

Base(int a) { cout << "Base(int)" << enld; }

~Base() { cout << "~Base()" << enld; }

};


class Derived : public Base

{

Derived() /* : Base() -> 안쓰면 이게 기본*/ { cout << "Derived()" << enld; }

Derived(int a) /* : Base(a) -> 이렇게 써도 됨*/ { cout << "Derived(int)"<< enld; }

~Derived() { cout << "~Derived()" << enld; /*~Base()*/}

};


int main()

{

Derived d();

"Base()"

"Derived()"

"~Derived()"

"~Base()"


Derived d(1);

"Base()"

"Derived(int)"

"~Derived()"

"~Base()"

}



Q.1

class Animal

{

public:

Animal() {}

};

class Dog : public Animal

{

public:

Dog(){}

};

int main()

{

// 다음중 에러가 발생하는 것은?

Animal a; // 1 , Error

Dog d; // 2 , Error

}


Q.2

class Animal

{

protected:

Animal() {}

};

class Dog : public Animal

{

public:

Dog(){}

};

int main()

{

// 다음중 에러가 발생하는 것은?

Animal a; // 1 , Error

Dog d; // 2 , Ok

}


protected : 나는 객체를 만들수 없지만 내 하위개념은 객체를 만들수 있다.

현실세계에 없는 추상적인 개념쓸때 좋은 도구. Animal은 추상화된 개념이지만 Dog는 실체가 있음 이와 같은 경우.

728x90

'프로그래밍언어 > C++' 카테고리의 다른 글

객체 지향 디자인  (0) 2017.03.27
가상함수와 다형성  (0) 2017.03.27
STL 설계 철학  (0) 2017.03.19
알고리즘의 정책 변경  (0) 2017.03.19
STL 알고리즘 ( algorithm )  (0) 2017.03.19
Comments