[C++] C++ Constructor

JAsmine_log·2024년 5월 19일

C++

Constructor

클래스에서 사용하는 특별한 메서드(special method)로, 자동으로 객체를 생성한다. Constructor를 생성하기 위해서는 Class 이름뒤에 ()를 붙인다.
ex. ClassName()

Example

class MyClass {     // The class
  public:           // Access specifier
    MyClass() {     // Constructor
      cout << "Hello World!";
    }
};

int main() {
  MyClass myObj;    // Create an object of MyClass (this will call the constructor)
  return 0;
}

Constructor Parameter

Constructor에 parameter를 주면, 값을 초기화하여 사용할 수 있다.

Example

#include <iostream>
using namespace std;

class MyClass {     // The class
public:           	// Access specifier
	int height;
    int width;
    
    MyClass(int a, int b) {     // Constructor
     	height=a;
        width=b;
    }
};

int main() {
  MyClass myObj1(4, 6);			// Constructor with Prarmeters
  MyClass myObj2(5, 7);
  
   // Print values
  cout << myObj1.height << " " << myObj1.width << endl;
  cout << myObj2.height << " " << myObj2.width << endl;
  return 0;
}

Referecne

[1] https://www.w3schools.com/cpp/cpp_constructors.asp

profile
Everyday Research & Development

0개의 댓글