[C++] struct 와 class 의 차이

김세희·2025년 7월 17일

주요 차이점

접근 제어자
struct: 기본적으로 모든 멤버가 public 으로 선언. 상속도 마찬가지
class: 기본적으로 모든 멤버가 private 으로 선언. 상속도 마찬가지

struct 또한 클래스 타입이기 때문에 객체화도 되고 생성자도 만들 수 있다.



#include <iostream>
#include <string>

using namespace std;

class student
{
public:
   string name;
   int age;  
  
};
struct address
{
   address(string emailInput="test", string phoneInput="test")
   	:email(emailInput), phone(phoneInput){}
   string email;
   string phone;

   void print()
   {
       cout<<"email: "<<email<<"\n";
       cout<<"phone: "<<phone<<"\n";
   }
};
int main(int argc, char* argv[])
{
   struct address student1={"email@com", "01012345678"};
   struct address student2;
  
   student1.print();
   student2.print();
  
   return 0;
}

C++에서 class와 struct로 선언된 사용자 정의 타입은 모두 클래스로 간주된다.
따라서 클래스가 구조체를 상속받거나 구조체가 클래스를 상속받을 수 있다.

#include <iostream>
#include <string>

using namespace std;

class student
{
public:
    student(string nameInput="name", int ageIntput=1):name(nameInput), age(ageIntput){}
    string name;
    int age;   
    
};
struct address : public student
{
    address(string emailInput="test", string phoneInput="test"):
        student() ,email(emailInput), phone(phoneInput){}
    string email;
    string phone;

    void print()
    {
        cout<<name<<" "<<age<<"\n";
        cout<<"email: "<<email<<"\n";
        cout<<"phone: "<<phone<<"\n";
    }
    private:
    string secret;
};

C++ 에서 상속은 클래스 타입 간에 이루어지는 관계이다.
int, float 같이 기본 자료형은 클래스 타입이 아니므로 상속의 대상이 될 수 없다.

C++ 에서 사용자가 객체 지향적인 방식으로 데이터와 함수를 캡슐화하고 상속 및 다형성을 구현하기 위해 정의하는 클래스 타입은 오직 class와 struct 키워드를 통해서만 생성할 수 있다.
나머지 타입들은 언어의 기본적인 구성요소이거나 특수한 목적을 가진 타입이다.

0개의 댓글