• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

m_i 값이 안바뀌는 이유가 뭔가요?

19.10.05 11:43 작성 조회수 213

1

//
//  main.cpp
//  inheritance_ex01
//
//  Created by Kevin on 04/10/2019.
//  Copyright © 2019 Kevin. All rights reserved.
//

#include <iostream>
using namespace std;

class Mother { // basic class
private:
    int m_i;
    
public:
    //Mother() {}
    
    Mother(const int& i_in) : m_i(i_in) {
        std::cout << "Mother constructor" << std::endl;
        std::cout << "m_i " << m_i << std::endl;
    }
    
    void setValue(const int& i_in) {
        std::cout << "i_in " << i_in << std::endl;
        m_i = i_in;
        std::cout << "m_i " << m_i << std::endl;
    }
    
    int getValue() {
        return m_i;
    }
};

class Child : public Mother {
private:
    double m_d;
    
public:
    Child(const int& i_in, const double& d_in) : Mother(i_in), m_d(d_in) {
        std::cout << "Child constructor" << std::endl;
        Mother::setValue(i_in);
    }
    
    void setValue(const int& i_in, const double& d_in) {
    }
    
    void setValue(const double& d_in) {
        m_d = d_in;
    }
    
    double getValue() {
        return m_d;
    }
}; // derived class

int main(int argc, const char * argv[]) {
    Mother mother(512);
    std::cout << mother.getValue() << std::endl;
    
    Child child(1024, 2048);
    std::cout << "m_i value : " << mother.getValue() << std::endl;
    // 왜 512인가요?
    std::cout << "m_d value : " << child.getValue() << std::endl;
    
    return 0;
}

답변 4

·

답변을 작성해보세요.

1

김영성님의 프로필

김영성

질문자

2019.10.06

원인은 찾았는데, 개념적인 이해를 이렇게 해도 될까요?

mother에서 상속받은 m_i는 mother의 m_i를 상속 받으면, child에 별개의 상속받은 m_i가 있다고 보면 되는 것인가요?

상속을 받으면, 동일한 m_i를 공유 한다고 생각을 했었습니다.

0

김영성님의 프로필

김영성

질문자

2019.10.06

감사합니다.. 강의 정말 많은 도움이 됩니다.. ^^

0

맞아요! 정확히 그 부분에서 오해를 하고 계신 것 같았습니다. class를 보통 쿠키틀에 비유를 하지요. 

0

코드를 실행시켜봤는데 왜 512가 아니라 다른 값이 나올거라고 생각하는 지가 궁금하네요. 상속이라는 개념에 조금 더 생각해보셔야할 것 같습니다.