Skip to content

Instantly share code, notes, and snippets.

@nkapliev
Last active Dec 7, 2017
Embed
What would you like to do?
Compilation error if field class does not have default constructor and the field was not initialized during pre-constructor initialization.
#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();
}
@nkapliev
Copy link
Author

nkapliev commented Dec 7, 2017

Output is:

A point has been initialized
A city has been initialized

@nkapliev
Copy link
Author

nkapliev commented Dec 7, 2017

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

@nkapliev
Copy link
Author

nkapliev commented Dec 7, 2017

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