NeuroWhAI의 잡블로그

[C++] 책 읽다가 본 충격적인 코드 - private 멤버 접근 방법 본문

개발 및 공부/언어

[C++] 책 읽다가 본 충격적인 코드 - private 멤버 접근 방법

NeuroWhAI 2018. 1. 3. 21:15


먼저 아래는 보통의 코드 입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// myclass.h
 
class MyClass
{
public:
    MyClass()
        : m_data(0)
    {
    
    }
    
private:
    int m_data;
    
public:
    void setData(int data)
    {
        if (data < 0)
        {
            data = 0;
        }
        
        m_data = data;
    }
    
    int getData() const
    {
        return m_data;
    }
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
 
#include "myclass.h"
 
 
 
 
using namespace std;
 
 
int main()
{
    MyClass foo;
    
    foo.setData(42);
    cout << foo.getData() << endl;
    
    foo.setData(-1);
    cout << foo.getData() << endl;
    
    
    return 0;
}

data는 음수가 될 수 없도록 설계한 클래스 입니다.


위 코드의 실행결과는 당연히
42
0
입니다.

그런데 아래 코드를 봅시다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
 
#define private public
#include "myclass.h"
#undef private
 
 
 
 
using namespace std;
 
 
int main()
{
    MyClass foo;
    
    foo.setData(42);
    cout << foo.getData() << endl;
    
    foo.m_data = -1;
    cout << foo.getData() << endl;
    
    
    return 0;
}

42
-1

띠요오오옹???
원래라면 error: 'int MyClass::m_data' is private within this context 에러를 뱉겠지만
전처리 지시문 때문에 private가 public으로 바뀌어버렸습니다.

C++ API 설계 책의 Pimpl 이디엄 관련 항목이었는데
저런 코드는 상상도 못해서 충격을 좀 받았습니다. ㄷㄷ
(사실 상상도 못하는게 순수한거져 ㅎㅎ)
더 응용하면 const를 비 const로 만들수도 있고 비 const를 const로 만들수도 있고 올ㅋ




Comments