Scribbling

[C++] 전문가를 위한 C++ - Chapter 8 본문

Computer Science/C++

[C++] 전문가를 위한 C++ - Chapter 8

focalpoint 2023. 10. 7. 02:35

 

1. Default Constructor

In C++, when making an array, we cannot explicitly call a constructor other than the default one.

 

2. Converting Constructor

C++ compiler may implicitly convert a value to an object. (In this case, integer to Cell object)

class Cell {
public:
	int num = 0;

	Cell() = default;
	Cell(int num) {
		this->num = num;
	}
};


int main() {
	
	Cell cell1{ 4 };
	cell1 = 5;
	cout << cell1.num << endl;
}

To prevent such, we can use "explicit" keyword.

class Cell {
public:
	int num = 0;

	Cell() = default;
	explicit Cell(int num) {
		this->num = num;
	}
};


int main() {
	
	Cell cell1{ 4 };
	cell1 = 5;
	cout << cell1.num << endl;
}

 

3. Copy Constructor & Assignment Operator

The copy constructor is only used when initiating an object.

In the below, cell 2 and cell 3 call the copy constructor.

int main() {
	
	Cell cell1{ 5 };
	Cell cell2{ cell1 };
    Cell cell3 = cell1;
}

*** When a function returns an object, it calls the copy constructor.

*** Constructor Initializer also calls the copy constructor.

'Computer Science > C++' 카테고리의 다른 글

[C++] lower_bound  (0) 2024.02.06
[C++] Deque<int>  (0) 2024.02.06
[C++] find, deque, bfs, structured binding  (0) 2023.09.30
[C++] Smart pointers  (0) 2023.09.30
[C++] 전문가를 위한 C++ - Chapter 2  (1) 2023.09.21