상속받은 함수를 오버라이딩하기

상속을 사용하는 일반적인 경우엔

상속을 해주는 부모클래스와 상속을 받는 자식클래스는
보통 기능차이가 많지않을 수 있다.

이때 함수오버라이딩을 유용하게 사용할수 있다.

함수 오버라이딩할때 부모클래스의 함수를 사용하고 싶다면 부모클래스이름은 선언한다.

Base::Print();


다형성에서 사용된다.

<< operator 를 사용하고 싶으면 static_cast해서 사용한다.

out << static_cast<Base>(b) << endl;

 

#include <iostream>

using namespace std;

class Base {
protected:
	int m_i;

public:
	Base(int a)
		: m_i(a)
	{

	}

	void Print() {
		cout << "I'm  Base" << endl;
	}

	friend std::ostream & operator << (std::ostream & out, const Base &b) {
		out << "Base opertator";
		return out;
	}
};

class Derived : public Base {
public:
	double m_d;

	Derived(int a)
		:Base(a) {

	}

	void Print() {
		Base::Print();
		cout << "I'm  Derived" << endl;
	}

	friend std::ostream & operator << (std::ostream & out, const Derived &b) {
		out << static_cast<Base>(b) << endl;
		out << "Derived opertator";
		return out;
	}
};

int main()
{
	Base b(5);
	Derived d(2);

	b.Print();
	d.Print();
	cout << b << endl;
	cout << d << endl;
	return 0;
}

상속과 접근지정자

클래스에서 접근지정자로 접근권한을 제한할 수 있다.
상속도 마찬가지로 접근지정자로 제어할 수 있다.

protected는 외부에선 접근 불가능하지만 자식클래스에서 접근가능하다.

유도된 클래스(자식클래스)에 새로운 기능 추가할때
protected를 사용하면 private 변수일때 public에 getValue()를 만들어 사용하지않고 퍼포먼스를 향상시킬 수 있다.

 

#include <iostream>
using namespace std;
class Base {
protected:
	int m_public;

public:
	Base(const int & a) 
	:m_public(a){

	}
};

class Derived : public Base
{
public:
	Derived(const int & a) 
	:Base(a){
	
	}

	void setValue(int value) {
		Base::m_public + value;
	}
};
int main()
{

	return 0;
}


다중상속일때 단계가 높은 부모클래스에 접근하지 못하게할때 사용한다.

즉, private 으로 상속하면 다중상속일때 하하위 클래스가 직접접근하지 못하게한다.

 

#include <iostream>

using namespace std;

class Base {
public:
	int m_public;

	int funPublic() {
		return 0;
	}
protected:
	int m_protected;
	int funProtected() {
		return 0;
	}
private:
	int m_private;
};

class Derived : public Base
{
public:
	Derived() {
		m_public = 123;
		m_protected = 123;
		//m_private = 123;
		funPublic();
		funProtected();
	}
};

class Derived2 : protected Base
{
public:
	int a;
	Derived2() {
		m_public = 123;
		m_protected = 123;
		//m_private = 123;
		a = funPublic();
		a = funProtected();
	}
protected:
	int a2 = 0;
};

class Derived3 : private Base
{
public:
	int a;

	Derived3() {
		m_public = 123;
		m_protected = 123;
		//m_private = 123;
		a = funPublic();
		a = funProtected();
	}

};

class GrandChild : public Derived3 {
public:
	GrandChild() {
		//m_public; 불가능하다
		cout << a << endl;
	}
};

int main()
{
	Derived der;

	der.m_public = 123;
	//base.m_protected = 123;
	//base.m_private = 123;
	
	//protected 상속
	Derived2 der2;
	//der.m_public = 123;

	//private 상속
	Derived3 der3;
	//der.m_public = 123;


	return 0;
}

유도된 클래스들의 생성순서
Derived

 

기본지식

접근지정자
private 은 자식도 사용못한다.
protected는 자식은 사용가능하다.

:initalizer list는 안된다. 이유는?
클래스가 생성되는 순서를 알아야한다.

자식클래스를 객체생성하면 부모클래스가 먼저 생성되는것을 확인할 수 있다.

debug를 해보게되면
부모객체,자식객체변수를 쓰레기값으로 생성되고 
부모객체부터 초기화하고 자식객체의 변수들을 초기화되는걸 볼 수 있다. 

자식클래스는 부모클래스에 있는걸 다 사용할 수 있기에
부모클래스부터 정의해서 사용할 수 있게한다.

부모클래스의 constructor를 항상 먼저 실행시킨다.

다중상속을 하여도 맨위의 부모클래스부터 연쇄적으로초기화한다.

소멸자 Destructor는 반대로 소멸된다. 자식부터 소멸된다.

 

아래코드의 생성 순서를 보자(주석으로 써놓았다.)

1.객체생성한다.

2. 자식클래스 생성자로 온다.

3.부모클래스 생성자를 실행한다.

4.자식클래스의 생성자를 초기화한다.

 

#include <iostream>

using namespace std;

class Mother
{
public:
	int m_i;
	//3.부모클래스 생성자를 실행한다.
	Mother() :m_i(1){
		cout << "Mother Constructor" << endl;
	}
	~Mother() {
		cout << "Mother Destructor" << endl;
	}
	Mother(const int &a) :m_i(a) {
		cout << "Mother Constructor" << endl;
	}
};

class Child : public Mother 
{
public:
	double m_d;
	//2. 자식클래스 생성자로 온다.
	Child()
	: //내부적으로 숨어있다.Mother(),
		//4.자식클래스의 생성자를 초기화한다.
		m_d(1.0){
		cout << "Child Constructor" << endl;
	}
	~Child() {
		cout << "Child Destructor" << endl;
	}
};


class A : public Child
{
public:
	A() {
		cout << "A" << endl;
	}
	~A() {
		cout << "A Destructor" << endl;
	}
};
int main()
{
	//1.객체생성
	Child c1;
	
	return 0;
}

Inheritance (is-a relationship)

상속이 도움되는 이유를 구체적인 사례를 보자.

학생,교수 클래스 모두 이름이 있다.
학생,교수의 공통점은 사람이다.

사람의 기본적인 데이터(이름)를 부모클래스로 생성한다.
즉, 중복되는 데이터만 부모클래스로 뽑아낸다.

부모클래스만 사용하는기능은 부모클래스에 정의한다.
set,get등이 있다.

부모클래스의 기능을 사용가능한건 this로 확인할 수 있다.

중복되는 기능을 유지보수할때 부모클래스만 수정하면되게된다.

 

아래코드는 교수,학생클래스를 생성할때 공통된 데이터인

이름을 부모클래스로 생성해 상속받는다.

 

Person.h

#pragma once
#include <string>
#include <iostream>

class Person 
{
private:
	std::string m_name;

public:
	Person(const std::string & name) 
	:m_name(name) {}

	void setName(const std::string & name) {
		m_name = name;
	}

	std::string getName() const{
		return m_name;
	}

	void doNothing() const
	{
		std::cout << m_name << " doNothing" << std::endl;
	}
};

Student.h

#pragma once

#include "Person.h"

class Student : public Person{
private:
	int m_intel;

public:
	Student(const std::string & name = "noName", const int & intel = 0)
		: Person(name), m_intel(intel) {}

	void setIntel(const int & intel) {
		m_intel = intel;
	}

	int getIntel()
	{
		return m_intel;
	}

	friend std::ostream & operator << (std::ostream & out, const Student & s) {
		out << s.getName() << " " << s.m_intel;
		return out;
	}
};

Teacher.h

#pragma once

#include "Person.h"

class Teacher :public Person
{
private:


public:
	Teacher(const std::string & name = "noName")
		:Person(name) {

	}

	friend std::ostream & operator << (std::ostream & out, const Teacher & t1) {
		out << t1.getName();
		return out;
	}

};

main.cpp

#include "Student.h"
#include "Teacher.h"

using namespace std;

int main()
{
	string name = "";
	Student s("Jack Jack");
	Teacher t("Choi");

	cout << s.getName() << endl;
	cout << t.getName() << endl;

	s.doNothing();
	t.doNothing();

	return 0;
}

객체지향의 핵심
is-a relationship
inheritance

자식클래스는 상속받은 부모클래스의 기능을 모두 사용할 수 있다.
상속을 받은 클래스(자식클래스)를 derived class라고도 한다.

여러클래스에 일반화된것들을 뽑아서 부모클래스로 생성한다.
즉, 여러클래스에서 재사용이 매우용이하다.

부모클래스,자식클래스에 이름이 같은 메소드가 있다면 자식클래스의 메소드가 실행된다.
private는 자식에게도 허용이안된다. 이럴때 protected를 사용거나 부모클래스 생성자를 사용한다.

자식클래스의 생성이유는 부모클래스의 기능과 자식클래스의 기능을 합쳐쓰기 위함이다.

자식클래스에서 생성자Constructor를 만들려면 부모클래스를 불러와 정의해준다.

당연히 자식클래스에서 부모클래스를 사용할수 있기 때문에

부모클래스가 먼저생성되고 자식클래스가 생성된다. 

즉, 자식클래스가 생성될때 부모클래스의 생성자를 같이 실행한다.

즉, 기본생성자가 없으면 정의 해주어야한다.
아니면 자식클래스 생성자에서 부모클래스생성자를 선언해준다.

 

#include <iostream>

using namespace std;

class Mother {
private:
	int m_i;

public:
	//Mother(){}

	Mother(const int & i_in) 
	: m_i(i_in) {
		cout << "constructor" << endl;
	}

	void setValue(const int & i) {
		m_i = i;
	}

	int getValue() {
		return m_i;
	}
};

class Child : public Mother
{
private:
	double m_d;

public:
	Child(const double & d_in, const int & i_in) 
	: Mother(i_in),m_d(d_in)
	{}

	void setValue(const double & d_in,const int & i_in) {
		Mother::setValue(i_in);
	}

	void setValue(const double & d) {
		m_d = d;
	}

	double getValue() {
		return m_d;
	}
};

//Mother 클래스 재사용
class Daughter : public Mother
{

};

int main()
{
	Mother mother(11);
	mother.setValue(1234);
	cout << mother.getValue() << endl;

	Child child(12,222);
	cout << child.getValue() << endl;
	cout << child.Mother::getValue() << endl;

	return 0;
}

+ Recent posts