Skip to content

Instantly share code, notes, and snippets.

@nkapliev
Last active December 7, 2017 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkapliev/a1235e342233d1f9596a5d5e99a0b76c to your computer and use it in GitHub Desktop.
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.
#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

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