화살표 연산자 방식으로 초기화하는 방법도 있지만, 객체 생성 시 콜론으로 초기화를 함께하는 방법도 있다.
줄 수가 줄어듬
객체의 생성과 초기화가 한 번에 이루어짐
Sample1::Sample1(char p1, int p2, float p3) {
std::cout << "Constructor called" << std::endl;
this->a1 = p1;
std::cout << "this->a1 = " << this->a1 << std::endl;
this->a2 = p2;
std::cout << "this->a2 = " << this->a2 << std::endl;
this->a3 = p3;
std::cout << "this->a3 = " << this->a3 << std::endl;
return;
}
Sample2::Sample2(char p1, int p2, float p3) : a1(p1), a2(p2), a3(p3) {
std::cout << "Constructor called" << std::endl;
std::cout << "this->a1 = " << this->a1 << std::endl;
std::cout << "this->a2 = " << this->a2 << std::endl;
std::cout << "this->a3 = " << this->a3 << std::endl;
return;
}
#include "Sample1.class.hpp"
#include "Sample2.class.hpp"
#include <iostream>
int main() {
Sample1 instance1('a', 45, 4.2f);
Sample2 instance2('z', 13, 3.14f);
return 0;
}
#include "Sample1.class.hpp"
# include <iostream>
Sample1::Sample1(char p1, int p2, float p3) {
std::cout << "Constructor called" << std::endl;
this->a1 = p1;
std::cout << "this->a1 = " << this->a1 << std::endl;
this->a2 = p2;
std::cout << "this->a2 = " << this->a2 << std::endl;
this->a3 = p3;
std::cout << "this->a3 = " << this->a3 << std::endl;
return;
}
Sample1::~Sample1(void) {
std::cout << "Destructor called" << std::endl;
return ;
}
#ifndef SAMPLE1_CLASS_H
# define SAMPLE1_CLASS_H
class Sample1 {
public:
char a1;
int a2;
float a3;
Sample1(char p1, int p2, float p3);
~Sample1(void);
};
#endif
#include "Sample2.class.hpp"
# include <iostream>
Sample2::Sample2(char p1, int p2, float p3) : a1(p1), a2(p2), a3(p3) {
std::cout << "Constructor called" << std::endl;
std::cout << "this->a1 = " << this->a1 << std::endl;
std::cout << "this->a2 = " << this->a2 << std::endl;
std::cout << "this->a3 = " << this->a3 << std::endl;
return;
}
Sample2::~Sample2(void) {
std::cout << "Destructor called" << std::endl;
return ;
}
#ifndef SAMPLE2_CLASS_H
# define SAMPLE2_CLASS_H
class Sample2 {
public:
char a1;
int a2;
float a3;
Sample2(char p1, int p2, float p3);
~Sample2(void);
};
#endif