How do you separate interface from implementation with data members that are not static?

Viewed 38
#include <iostream>

struct Person {
public:
    static int staticNumber;
    static std::string staticText;
    int regularNumber;
    std::string regularText;
};

// I know how do it for static types
int Person::staticNumber = 0;

std::string Person::staticText = "Default";

// How would I do it for regular types?

int Person::regularNumber = 0; // I get an error here

std::string Person::regularText = "@"; // I get an error here

int main() {
    Person::staticNumber += 10;
    std::cout << Person::staticNumber << "\n";
    Person::staticText += "!";
    std::cout << Person::staticText << "\n";
} 

As you can see from the code snippet it works fine with static data members. But as soon as I do it with ones without the word static I get an error. How do you separate interface from implementation with data members that are not static?

1 Answers

A non-static data member is associated with a specific instance of that object. To modify it, you create an object, then modify that object's data.

Person p;

p.regularNumber = 1234;

That said, public access to data members tends to be frowned upon. The point of object orientation is largely to support higher-level operations, not just collect related data together.

Related