Scientia Conditorium

[C++] struct 와 class 의 차이점 본문

프로그래밍/C++

[C++] struct 와 class 의 차이점

크썸 2022. 9. 17. 23:49

[C++] struct 와 class 의 차이점

 

결론부터 말하자면 C++에서 struct와 class의 차이점은 없다.

먼저 isocpp의 답변부터 살펴보도록 하자.

https://isocpp.org/wiki/faq/classes-and-objects#struct-vs-class

 

Standard C++

 

isocpp.org

 

What’s the difference between the keywords struct and class?

The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults.

struct and class are otherwise functionally equivalent.

Enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that’s the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.

C++에서 struct의 접근제어자(Access Modifier) 기본값은 public 이지만, class는 private 입니다.

이 두 개를 제외하고는 기능적으로 동등합니다.

만약 이 두 개가 다르다면 컴퓨터는 이를 구분할 줄 알아야하는데 그렇지 않습니다.

 

C++은 C언어에서 OOP 개념이 추가되어 나온 언어입니다. 새롭게 정립된 언어구조가 아닙니다.

C언어에서 Class가 없었기 때문에 C++에서의 class는 누군가가 새롭게 만든 것 입니다.

어셈블리어에서는 구분하지 않지만, 컴파일러는 구분합니다.

왜냐면 기본 접근제어자가 다르기 때문이죠.

 

기능적으로 동일하기 때문에 사용자 입장에서는 이를 구분해서 사용해야 합니다.

보통 struct는 순수 그룹지어진 데이터로 사용하며, class는 이를 확장하여 멤버함수까지 추가하는 형태로 사용합니다.

이와 관련하여 재밌는 참고자료들을 나열해드립니다.

 

1. 포프TV : 코딩스탠다드 : struct vs class

https://youtu.be/OMiEwfmfdng

 

2. MSDN : Choosing Between Class and Struct

https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct