In my example I created a class Person which has a member object: struct data. This object contains data about person. Each time a Person-Object is created, also the data-object shall be initialized.
Observation: When adding object initializer to code (1) at class constructor I get failure message:
incomplete type is not allowedC/C++(70)
class person {
public:
struct data;
person() { /* (1) */
person::data myPersonData;
}
private:
};
So here is how I practice it now:
- No struct object initialization myPersonData in class person constructor (class_person.hpp)
- Create person object in main.cpp
- Create myPersonData in main.cpp (I would like to save this initialization and put it to class contructor)
The whole example looks like this:
// class_person.hpp
#include <iostream>
#include <string>
class person {
public:
struct data;
private:
};
struct person::data {
std::string name = "John";
int age = 42;
int weight = 75;
};
_
// main.cpp
#include <iostream>
#include "class_person.hpp"
void outputPersonData(person::data myPerson) {
std::cout << myPerson.name << "\n";
std::cout << myPerson.age << "years\n";
std::cout << myPerson.weight << "kg\n";
};
int main() {
person John;
person::data myPersonData;
outputPersonData(myPersonData);
getchar();
return 0;
}
struct data;just declaresperson::data; the struct is lacking a definition and is thus incomplete