OOP (Object-Oriented Programming)는 객체 지향 프로그래밍의 약자로 프로그램을 객체의 모음으로 구성하는 프로그래밍 방법론이다.
설계도또는 틀에 비유할 수 있으며, 객체가 가져야 할 공통적인 속성(데이터)과 행동(메소드)을 정의실체class BankAccount
{
private:
int balance; // 외부에서 직접 접근 불가
public:
BankAccount(int initial) : balance(initial) {}
void Deposit(int amount) // 공개 메서드
{
if (amount > 0)
balance += amount;
}
bool Withdraw(int amount) // 공개 메서드
{
if (amount > 0 && balance >= amount)
{
balance -= amount;
return true;
}
return false;
}
int GetBalance() const // 읽기 전용 인터페이스
{
return balance;
}
};
balance는 private이라 외부 코드에서 account.balance = -100 이런 식으로 막 건드릴 수 없다.
또한, 입출금 로직은 내부에서 숨겨져 있고, 외부에는 메서드라는 인터페이스만 노출된다.
class Shape // 추상적인 개념
{
public:
virtual void Draw() = 0; // 순수 가상 함수 → 인터페이스만 정의
virtual double GetArea() const = 0;
virtual ~Shape() = default;
};
class Circle : public Shape // 구체적인 원
{
public:
Circle(double r) : radius(r) {}
void Draw() override
{
// 원을 그리는 실제 코드
}
double GetArea() const override
{
return 3.14159 * radius * radius;
}
private:
double radius;
};
class Rectangle : public Shape // 구체적인 사각형
{
public:
Rectangle(double w, double h) : width(w), height(h) {}
void Draw() override
{
// 사각형을 그리는 실제 코드
}
double GetArea() const override
{
return width * height;
}
private:
double width;
double height;
};
Shape는 도형이라는 추상 개념만 정의하고 Circle, Rectangle에서 구체적인 구현을 한다.
class Animal
{
public:
void Eat()
{
// 공통 먹기 로직
}
virtual void MakeSound()
{
// 기본 소리 (필요하면 비워 둘 수도 있음)
}
};
class Dog : public Animal
{
public:
void MakeSound() override
{
std::cout << "Woof!" << std::endl;
}
};
class Cat : public Animal
{
public:
void MakeSound() override
{
std::cout << "Meow!" << std::endl;
}
};
위 예시에서 Dog, Cat은 Animal의 자식 클래스이다.
Eat() 같은 공통 기능은 부모 클래스인 Animal에 두고, 각 동물마다 다른 MakeSound()만 Override해서 구현하고 있다.
void MakeAnimalSound(Animal* animal)
{
animal->MakeSound(); // 어떤 소리가 날지는 실제 객체 타입에 따라 달라짐
}
int main()
{
Animal* a1 = new Dog();
Animal* a2 = new Cat();
MakeAnimalSound(a1); // Dog::MakeSound() -> "Woof!"
MakeAnimalSound(a2); // Cat::MakeSound() -> "Meow!"
delete a1;
delete a2;
}
MakeAnimalSound 함수는 인자로 Animal*만 알고 있지만, 실제로 들어오는 객체가 Dog인지 Cat인지에 따라 런타임에 다른 함수가 호출된다.