29

This is really a question of good form/best practices. I use structs in C++ to form objects that are designed to basically hold data, rather than making a class with a ton of accessor methods that do nothing but get/set the values. For example:

struct Person {
    std::string name;
    DateObject dob;
    (...)
};

If you imagine 20 more variables there, writing this as a class with private members and 40-something accessors is a pain to manage and seems wasteful to me.

Sometimes though, I might need to also add some sort of minimal functionality to the data. In the example, say I also sometimes need the age, based on dob:

struct Person {
    std::string name;
    DateObject dob;
    (...)
    int age() {return calculated age from dob;}
}

Of course for any complex functionality I would make a class, but for just a simple functionality like this, is this "bad design"? If I do use a class, is it bad form to keep the data variables as public class members, or do I just need to accept it and make classes with a bunch of accessor methods? I understand the differences between classes and structs, I'm just asking about best practices.

4
  • Writting accesor methods (getter/setter) is a good idea. If you just google a bit you will probably find tons of discussion about this topic. Tip: Most IDEs provide the functionality to generate getter and setter automatically. Mar 22, 2013 at 14:24
  • 2
    class and struct types differ in that the default access control of a class is private, and the default access control of a struct is public. Use of the keywords outside of creating a type can differ slightly... but you seem to be investing a lot of energy into the difference between the word struct and class in a type. It can be used for documentation in a particular project, but that is project specific. Mar 22, 2013 at 14:24
  • 2
    There's also the option of a free function int age(const Person& person). Not everything has to be an Object with Methods.
    – molbdnilo
    Mar 22, 2013 at 14:27
  • Possible duplicate of stackoverflow.com/questions/3380633/…?
    – Polar
    Mar 22, 2013 at 14:57

7 Answers 7

27

I think there are two important design principles to consider here:

  1. Hide a class's representation through an interface if there is some invariant on that class.

    A class has an invariant when there is such thing as an invalid state for that class. The class should maintain its invariant at all times.

    Consider a Point type that represents a 2D geometric point. This should just be a struct with public x and y data members. There is no such thing as an invalid point. Every combination of x and y values is perfectly fine.

    In the case of a Person, whether it has invariants depends entirely on the problem at hand. Do you consider such things as an empty name as a valid name? Can the Person have any date of birth? For your case, I think the answer is yes and your class should keep the members public.

    See: Classes Should Enforce Invariants

  2. Non-friend non-member functions improve encapsulation.

    There's no reason your age function should be implemented as a member function. The result of age can be calculated using the public interface of Person, so it has no reason to be a member function. Place it in the same namespace as Person so that it is found by argument-dependent lookup. Functions found by ADL are part of the interface of that class; they just don't have access to private data.

    If you did make it a member function and one day introduced some private state to Person, you would have an unnecessary dependency. Suddenly age has more access to data than it needs.

    See: How Non-Member Functions Improve Encapsulation

So here's how I would implement it:

struct Person {
  std::string name;
  DateObject dob;
};

int age(const Person& person) {
  return calculated age from person.dob;
}
4
  • 2
    Excellent answer, and exactly the type of info I was looking for, thanks!
    – amnesia
    Mar 22, 2013 at 20:03
  • I agree with this answer. I'd also add that defining age as a member function is poor control coupling- callers would have to pass the current date to the method in order to have a good sense of what it's doing, or a current date would have to be retrieved from elsewhere, which would not be obvious to the caller. age exposes more of the type's implementation to the client interface than is needed. It might reasonably be kept as a member function if this struct were guaranteed to never become more complex, but even then I'd at least declare it inline and add a currentDate parameter. Oct 6, 2015 at 17:25
  • @Joseph Mansfield "Place it in the same namespace as Person", wouldn't we expect to see a namespace PeopleStuff {...} encapsulating your code block then? Or is it enough for age() to be in the same file?
    – jigglypuff
    May 9, 2018 at 12:55
  • "Place it in the same namespace as Person so that it is found by argument-dependent lookup. Functions found by ADL are part of the interface of that class; they just don't have access to private data." == mind blown. nobism asks a good question, could you elaborate a bit more on the specifics of this?
    – Dale
    May 23, 2019 at 5:47
6

In C++, Structs are classes, with the only difference (that I can think of, at least) being that in Structs members are public by default, but in classes they are private. This means it is perfectly acceptable to use Structs as you are - this article explains it well.

1

In C++, the only difference between structs and classes are that structs are publicly visibly by default. A good guideline is to use structs as plain-old-data (POD) that only hold data and use classes for when more functionality (member functions) is required.

You may still be wondering whether to just have public variables in the class or use member functions; consider the following scenario.

Let's say you have a class A that has a function GetSomeVariable that is merely a getter for a private variable:

class A
{
    double _someVariable;

public:
    double GetSomeVariable() { return _someVariable; }
};

What if, twenty years down the line, the meaning of that variable changes, and you have to, let's say, multiply it by 0.5? When using a getter, it is simple; just return the variable multiplied by 0.5:

    double GetSomeVariable() { return 0.5*_someVariable; }

By doing this, you allow for easy maintainability and allow for easy modification.

1
1

If you want some data holder then prefer struct without any get/set methods.

If there is more to it, as in this case "Person".

  1. It models real world entity,
  2. Has definite state and behaviour,
  3. Interacts with external world,
  4. Exhibits simple/complex relationship with other entities,
  5. it may evolve overtime,

then it is a perfect candidate for a class.

0
0

"Use a struct only for passive objects that carry data; everything else is a class."

say google guidlines, I do it this way and find it a good rule. Beside that I think you can define your own pragmatics, or deviate from this rule if it really makes sense.

0

I don't want to sparkle a holy war here; I usually differentiate it in this way:

  • For POD objects (i.e., data-only, without exposed behavior) declare the internals public and access them directly. Usage of struct keyword is convenient here and also serves as a hint of the object usage.
  • For non-POD objects declare the internals private and define public getters/setters. Usage of class keyword is more natural in these cases.
0

For just clearing the confusion for some! And easy picking! Here some points!

In struct! you can have encapsulation and visibility operators (make private or public)! Just like you do with classes!

So the statement that some say or you may find online that say: one of the differences is that structures have no visibility operator and ability to hide data, is wrong!

You can have methods just like in classes!

Run the code bellow! And you can check it compiles all well! And run all well! And the whole struct work just like class!

Mainly the difference is just in the defaulting of the visibility mode!

Structures have it public! Classes privates by default!

#include<iostream>
#include<string>

using namespace std;

int main(int argv, char * argc[]) {
    struct {
        private:
            bool _iamSuperPrivate = true;
            void _sayHallo() {
                cout << "Hallo mein Bruder!" << endl;
            }
        public:
            string helloAddress = "";
            void sayHellow() {
                cout << "Hellow!" << endl;
                
                if (this->helloAddress != "") {
                    cout << this->helloAddress << endl;
                }

                this->_sayHallo();
            }
            bool isSuperPrivateWorking() {
                return this->_iamSuperPrivate;
            }
    } testStruct;

    testStruct.helloAddress = "my Friend!";
    testStruct.sayHellow();

    if (testStruct.isSuperPrivateWorking()) {
        cout << "Super private is working all well!" << endl;
    } else {
        cout << "Super private not working LOL !!!" << endl;
    }

    return 0;
}

enter image description here

In memory they are the same!

I didn't check myself! But some say if you make the same thing! The compiled assembly code will come the same between a struct and a class! (to be checked!)

Take any class and change the name to typedef struct ! You'll see that the code will still works the same!

class Client {

}

Client client(...);

=>

typedef struct Client {
 ....
} Client;

Client client(...);

If you do that all will works the same! At least i know that does in gcc!

YOu can test! In your platform!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.