Last active
December 7, 2017 12:50
-
-
Save nkapliev/a1235e342233d1f9596a5d5e99a0b76c to your computer and use it in GitHub Desktop.
Compilation error if field class does not have default constructor and the field was not initialized during pre-constructor initialization.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
class Point { | |
public: | |
int x; | |
int y; | |
Point() { | |
std::cout << "A point has been initialized by default constructor" << std::endl; | |
} | |
Point(int _x, int _y) { | |
std::cout << "A point has been initialized by Point(int, int) constructor" << std::endl; | |
x = _x; | |
y = _y; | |
} | |
}; | |
class City { | |
public: | |
Point position; | |
int population; | |
City(Point const & _position, int _population): position(_position), population(_population) { | |
std::cout << "A city has been initialized" << std::endl; | |
} | |
City() { | |
position = Point(10, 20); | |
} | |
}; | |
int main () { | |
Point p1 = Point(1, 2); | |
int population = 1000; | |
City c1 = City(p1, population); | |
City c2 = City(); | |
} |
rev2:
g++ ./default_constructor_2.cpp
./default_constructor_2.cpp: In constructor ‘City::City()’:
./default_constructor_2.cpp:24:9: error: no matching function for call to ‘Point::Point()’
City() {}
^
./default_constructor_2.cpp:24:9: note: candidates are:
./default_constructor_2.cpp:8:2: note: Point::Point(int, int)
Point(int _x, int _y) {
^
./default_constructor_2.cpp:8:2: note: candidate expects 2 arguments, 0 provided
./default_constructor_2.cpp:4:7: note: Point::Point(const Point&)
class Point {
^
./default_constructor_2.cpp:4:7: note: candidate expects 1 argument, 0 provided
rev3:
A point has been initialized by Point(int, int) constructor
A city has been initialized
A point has been initialized by default constructor
A point has been initialized by Point(int, int) constructor
There are 2 calls of Point
constructors for the second city!! Omg =(
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output is: