C++ Structs with Member Functions vs. Classes with Public Variables - c++

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.

I think there are two important design principles to consider here:
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
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;
}

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.

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.

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".
It models real world entity,
Has definite state and behaviour,
Interacts with external world,
Exhibits simple/complex relationship with other entities,
it may evolve overtime,
then it is a perfect candidate for a class.

"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.

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.

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;
}
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!

Related

Is it considered a good practice to define virtual get and set functions in C++?

If I have a simple 2 level class hierarchy as, for instance, this one:
// level 1
class Spare_Part{
private:
string name;
double price;
public:
Spare_Part();
string getName() { return name; }
double getPrice() { return price; }
virtual int getQuantity() { return -1; }; // may also define it as pure virtual
};
//level 2
class On_hand : public Spare_Part{
private:
int quantity;
string location;
public:
On_hand();
int getQuantity(){ return quantity; }
};
I want to have access to the member 'quantity' in the class 'On_hand' using a pointer to the base class 'Spare_part', so I made the 'getQuantity' function a virtual one. The code works fine, however, I have a feeling that I shouldn't have a get/set function (even though a virtual one) to access a member that is defined somewhere down the hierarchy. Is this really considered a bad practice that should be avoided by, for example, redesign of the classes?
Edit:The whole hierarchy is a little bit more complex. Alongside the 'On_hand' class there is class for parts available through contracted suppliers. The assumption is that I wouldn't be able to know how many parts are available through the suppliers and that is why 'quantity' is not included in the base class.
In this case, yes, this is bad practice; if it doesn't make sense to call getQuantity on a Spare_Part, it shouldn't compile. It should definitely not just return a flag value.
A redesign of your classes is probably necessary. Polymorphism should be used to model an is-a relationship, but your use is mostly to tag more data onto the class. You should use composition instead, perhaps making a Part_Store class which contains a Spare_Part, the quantity and location.
Let's try sorting things out.
There's nothing wrong in having a base calling its derived class to read a property. There are cases when it's known that every implementation of a base class must have a property, and the base class offers some functionalities that require that property, and that would be the same in all reasonable implementation, except for that property.
In such cases, there's absolutely nothing wrong in doing that.
As an alternative, if you're really sure that property is always going to be implemented with a simple fixed-type variable in any reasonable implementation, you can just add a protected variable to the base class, and let the implementations write to it.
It's all a matter of how much flexibility you need.
In your case, I think your conceptual inheritance model is flawed, which kind of empties your case of any meaning.
You are saying that On_hand derives from Spare_Part, which means, by definition, that every On_hand is a Spare_Part. This sounds weird to me, as being "on hand" sounds more like a quality of the spare part, than a special case of it. Maybe it'd be better to add an optional<On_Hand> to Spare_Part.
Or, even better, I suspect you want something like
struct On_Hand_Info { int quantity; string location; };
std::map<Spare_Part, On_Hand_Info> on_hand;
EDIT
Seen your last updates, maybe you should do something like:
struct IRetrievalInformation {
virtual int getQuantity() const=0;
};
class SparePart{
string name;
double price;
std::unique_ptr<IRetrievalInformation> retinfo;
public:
Spare_Part();
string const& getName() const { return name; }
double getPrice() const { return price; }
IRetrievalInformation const& getRetrievalInformation() const {
assert(retinfo);
return *retinfo;
}
IRetrievalInformation& getRetrievalInformation() {
return const_cast<IRetrievalInformation&>(
const_cast<SparePart const*>(this)->getRetrievalInformation()
);
}
};
class OnHandRetrieval : public IRetrievalInformation {
int quantity;
string location;
public:
On_hand();
int getQuantity() const final override { return quantity; }
};
PS: for God's sake, don't use both camelcase and underscores.
IMO, getters and setters must be considered as a bad practice and even an anti-pattern in almost all cases. The whole point of using OOP is to conceal implementation details (well, not only this, but this is also among others). Getters/setters are intended to expose implementation details, hence it ruins one of OOP principles. In the end, why not using old plain C structs, if you are using getters/setters? In such case, classes don't have any advantages over structs.
Well, there are cases when getters/setters may look good. The point is, there are too many programmers use them as replacement for structs. And the reason usually -- they don't understand how to design application in OOP manner.
In your case you don't need getters/setters. Just think about how you are gonna use this class further. Is it gonna have any extra functionality or just store some data? If so, maybe just use POD structs?
Further reading:
[1] http://www.javaworld.com/article/2073723/core-java/why-getter-and-setter-methods-are-evil.html
[2] http://www.yegor256.com/2014/09/16/getters-and-setters-are-evil.html
[3] http://typicalprogrammer.com/doing-it-wrong-getters-and-setters/
[4] Why use getters and setters?
[5] http://berryllium.nl/2011/02/getters-and-setters-evil-or-necessary-evil/

C++, please explain Classes to a Python user?

I'm trying to learn C++, Thanks to this article I find many similarity between C++ and Python and Javascript: http://www.cse.msu.edu/~cse231/python2Cpp.html
But I can't understand C++ Classes at all, they looks like Javascript prototypes, but not that easy.
For example:
//CLxLogMessage defined in header
class myLOG: public CLxLogMessage{
public:
virtual const char * GetFormat (){
return "Wavefront Object";
}
void Error (const std::string &msg){
CLxLogMessage::Error (msg.c_str ());
}
void Info (const std::string &msg){
CLxLogMessage::Info (msg.c_str ());
}
private:
std::string authoringTool;
};
Question: What is this Public/Private stuff at all!?
Edit: To be honest, I more enjoy C++ than Python, because I can learn truth meaning of everything, not simple automated commands, for example I preferred to use "int X" rather than "X" alone.
Thanks
myLOG is the name of the class. It inherits (look it up2) from CLxLogMessage and has the functions GetFormat (which is virtual and can be overridden by subclasses and called through base class pointers, look it up2), Error, and Info. It has the data member authoringTool which is a string.
The public and private stuff is access specifiers. Something in the private section can only be used by the class's member functions, and stuff in the public section can be used by anybody. There is another type of section called protected which means that only a class and its subclasses can access it, but nobody else1.
If you start adding stuff to a class without setting an access level first, it defaults to private.
You can have as many public, private, and protected sections as you want, in any order.
You need these different protection levels because you don't want other people messing with your data when you don't know about it. For example, if you had a class representing fractions, you wouldn't want someone to change the denominator to a 0 right under your nose. They'd have to go through a setter function which would check that the new value was valid before setting the denominator to it. That's just a trivial example though. The fact that Python does not have these is a shortcoming in the language's design.
All your questions would be answered if you had read a C++ book. There is no easy way out with C++. If you try to take one, you'll end up being a horrible C++ programmer.
1 You can let somebody else access private and protected members by declaring them as friends (look it up2).
2 Sorry for saying "look it up" so much, but it's too much information for me to put here. You'll have to find a good resource for these kinds of things.
Even though there's no way to give a comprehensive answer or anything near that, maybe think about it like this: classes are types. Consider this:
int n;
Here "int" is the name of a type, and "x" is a variable of type "int". There are basic types in C++, like "int", "char", "double". Now we can also make new, compound types from old types:
struct Foo
{
int n;
char c;
double d;
};
This defines a new type called "Foo", and Foo x; makes a new variable of that type. Now we can add some magic to the type "Foo":
class Foo
{
int n;
double d;
public:
Foo() : n(20), d(0.5) { } // "constructor"
};
The keywords struct and class almost mean the same thing, so we still have a compound type that has two member variables, n and d. However, this type also has a member function, and this one gets called every time you create a new Foo object. So when you say, Foo x;, then this variable's member value x.n will be set to 20 and x.d will be set to 0.5.
So that's that in a nutshell: Classes are types with built-in magic. And you are the magician.
The private and public is to do with data encapsulation, it means you can change the implementation of the class without affecting how it is used. I suggest reading up on some of the theory of object orientation.

Conventions for accessor methods (getters and setters) in C++

Several questions about accessor methods in C++ have been asked on SO, but none was able satisfy my curiosity on the issue.
I try to avoid accessors whenever possible, because, like Stroustrup and other famous programmers, I consider a class with many of them a sign of bad OO. In C++, I can in most cases add more responsibility to a class or use the friend keyword to avoid them. Yet in some cases, you really need access to specific class members.
There are several possibilities:
1. Don't use accessors at all
We can just make the respective member variables public. This is a no-go in Java, but seems to be OK with the C++ community. However, I'm a bit worried about cases were an explicit copy or a read-only (const) reference to an object should be returned, is that exaggerated?
2. Use Java-style get/set methods
I'm not sure if it's from Java at all, but I mean this:
int getAmount(); // Returns the amount
void setAmount(int amount); // Sets the amount
3. Use objective C-style get/set methods
This is a bit weird, but apparently increasingly common:
int amount(); // Returns the amount
void amount(int amount); // Sets the amount
In order for that to work, you will have to find a different name for your member variable. Some people append an underscore, others prepend "m_". I don't like either.
Which style do you use and why?
From my perspective as sitting with 4 million lines of C++ code (and that's just one project) from a maintenance perspective I would say:
It's ok to not use getters/setters if members are immutable (i.e. const) or simple with no dependencies (like a point class with members X and Y).
If member is private only it's also ok to skip getters/setters. I also count members of internal pimpl-classes as private if the .cpp unit is smallish.
If member is public or protected (protected is just as bad as public) and non-const, non-simple or has dependencies then use getters/setters.
As a maintenance guy my main reason for wanting to have getters/setters is because then I have a place to put break points / logging / something else.
I prefer the style of alternative 2. as that's more searchable (a key component in writing maintainable code).
2) is the best IMO, because it makes your intentions clearest. set_amount(10) is more meaningful than amount(10), and as a nice side effect allows a member named amount.
Public variables is usually a bad idea, because there's no encapsulation. Suppose you need to update a cache or refresh a window when a variable is updated? Too bad if your variables are public. If you have a set method, you can add it there.
I never use this style. Because it can limit the future of your class design and explicit geters or setters are just as efficient with a good compilers.
Of course, in reality inline explicit getters or setters create just as much underlying dependency on the class implementation. THey just reduce semantic dependency. You still have to recompile everything if you change them.
This is my default style when I use accessor methods.
This style seems too 'clever' to me. I do use it on rare occasions, but only in cases where I really want the accessor to feel as much as possible like a variable.
I do think there is a case for simple bags of variables with possibly a constructor to make sure they're all initialized to something sane. When I do this, I simply make it a struct and leave it all public.
That is a good style if we just want to represent pure data.
I don't like it :) because get_/set_ is really unnecessary when we can overload them in C++.
STL uses this style, such as std::streamString::str and std::ios_base::flags, except when it should be avoided! when? When method's name conflicts with other type's name, then get_/set_ style is used, such as std::string::get_allocator because of std::allocator.
In general, I feel that it is not a good idea to have too many getters and setters being used by too many entities in the system. It is just an indication of a bad design or wrong encapsulation.
Having said that, if such a design needs to be refactored, and the source code is available, I would prefer to use the Visitor Design pattern. The reason is:
a. It gives a class an opportunity to
decide whom to allow access to its
private state
b. It gives a class an
opportunity to decide what access to
allow to each of the entities who are
interested in its private state
c. It
clearly documents such exteral access
via a clear class interface
Basic idea is:
a) Redesign if possible else,
b)
Refactor such that
All access to class state is via a well known individualistic
interface
It should be possible to configure some kind of do's and don'ts
to each such interface, e.g. all
access from external entity GOOD
should be allowed, all access from
external entity BAD should be
disallowed, and external entity OK
should be allowed to get but not set (for example)
I would not exclude accessors from use. May for some POD structures, but I consider them a good thing (some accessors might have additional logic, too).
It doesn't realy matters the naming convention, if you are consistent in your code. If you are using several third party libraries, they might use different naming conventions anyway. So it is a matter of taste.
I've seen the idealization of classes instead of integral types to refer to meaningful data.
Something like this below is generally not making good use of C++ properties:
struct particle {
float mass;
float acceleration;
float velocity;
} p;
Why? Because the result of p.mass*p.acceleration is a float and not force as expected.
The definition of classes to designate a purpose (even if it's a value, like amount mentioned earlier) makes more sense, and allow us to do something like:
struct amount
{
int value;
amount() : value( 0 ) {}
amount( int value0 ) : value( value0 ) {}
operator int()& { return value; }
operator int()const& { return value; }
amount& operator = ( int const newvalue )
{
value = newvalue;
return *this;
}
};
You can access the value in amount implicitly by the operator int. Furthermore:
struct wage
{
amount balance;
operator amount()& { return balance; }
operator amount()const& { return balance; }
wage& operator = ( amount const& newbalance )
{
balance = newbalance;
return *this;
}
};
Getter/Setter usage:
void wage_test()
{
wage worker;
(amount&)worker = 100; // if you like this, can remove = operator
worker = amount(105); // an alternative if the first one is too weird
int value = (amount)worker; // getting amount is more clear
}
This is a different approach, doesn't mean it's good or bad, but different.
An additional possibility could be :
int& amount();
I'm not sure I would recommend it, but it has the advantage that the unusual notation can refrain users to modify data.
str.length() = 5; // Ok string is a very bad example :)
Sometimes it is maybe just the good choice to make:
image(point) = 255;
Another possibility again, use functional notation to modify the object.
edit::change_amount(obj, val)
This way dangerous/editing function can be pulled away in a separate namespace with it's own documentation. This one seems to come naturally with generic programming.
Let me tell you about one additional possiblity, which seems the most conscise.
Need to read & modify
Simply declare that variable public:
class Worker {
public:
int wage = 5000;
}
worker.wage = 8000;
cout << worker.wage << endl;
Need just to read
class Worker {
int _wage = 5000;
public:
inline int wage() {
return _wage;
}
}
worker.wage = 8000; // error !!
cout << worker.wage() << endl;
The downside of this approach is that you need to change all the calling code (add parentheses, that is) when you want to change the access pattern.
variation on #3, i'm told this could be 'fluent' style
class foo {
private: int bar;
private: int narf;
public: foo & bar(int);
public: int bar();
public: foo & narf(int);
public: int narf();
};
//multi set (get is as expected)
foo f; f.bar(2).narf(3);

Object oriented design suggestion

Here is my code:
class Soldier {
public:
Soldier(const string &name, const Gun &gun);
string getName();
private:
Gun gun;
string name;
};
class Gun {
public:
void fire();
void load(int bullets);
int getBullets();
private:
int bullets;
}
I need to call all the member functions of Gun over a Soldier object. Something like:
soldier.gun.fire();
or
soldier.getGun().load(15);
So which one is a better design? Hiding the gun object as a private member and access it with getGun() function. Or making it a public member? Or I can encapsulate all these functions would make the implementation harder:
soldier.loadGun(15); // calls Gun.load()
soldier.fire(); // calls Gun.fire()
So which one do you think is the best?
I would say go with your second option:
soldier.loadGun(15); // calls Gun.load()
soldier.fire(); // calls Gun.fire()
Initially it's more work, but as the system gets more complex, you may find that a soldier will want to do other things before and after firing their gun (maybe check if they have enough ammo and then scream "Die suckers!!" before firing, and mutter "that's gotta hurt" after, and check to see if they need a reload). It also hides from the users of the Soldier class the unnecessary details of how exactly the gun is being fired.
First off, you'd be violating the Law of Demeter by accessing the Gun from outside the Soldier class.
I would consider methods like these instead:
soldier.ArmWeapon(...);
soldier.Attack(...);
This way you could also implement your fist, knife, grenade, baseball bat, laser cat, etc.
The Law of Demeter would say to encapsulate the functions.
http://en.wikipedia.org/wiki/Law_of_Demeter
This way, if you want some type of interaction between the soldier and the gun, you have a space to insert the code.
Edit: Found the relevant article from the Wikipedia link:
http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf
The paperboy example is very, very similar to the soldier example you post.
Indeed, it depends a lot about how much control you want to have.
To model the real world, you might even want to completely encapsulate the gun object, and just have a soldier.attack() method. The soldier.attack() method would then see whether the soldier was carrying a gun, and what the state of the gun was, and fire or reload it as necessary. Or possibly throw the gun at the target and run away, if insufficient ammunition were present for either operation...
If you expose gun, you allow things beyond the member functions of the Gun, which is probably not a good idea:
soldier.gun = anotherGun; // where did you drop your old gun?
If you use getGun(), the calls look a little ugly, but you can add functions to Gun without modifying Soldier.
If you encapsulate the functions (which I recommend) you can modify the Gun or introduce other (derived) classes of Gun without changing the interface to Soldier.
Usually my decision is based on the nature of the container class (in this case, Soldier). Either it is entirely a POD or is not. If it's not a POD, I make all data members private and provide accessor methods. The class is a POD only if it has no invariants (i.e. there is no way an external actor can make its state inconsistent by modifying its members). Your soldier class looks more like a non-POD to me, so I would go to the accessor method option. If it would return a const reference or a regular reference is your own decision, based on the behaviour of fire() and the other methods (if they modify gun's state or not).
BTW, Bjarne Stroustrup talks a little about this issue in his site:
http://www.artima.com/intv/goldilocks3.html
A sidenote: I know that's not precisely what you asked, but I'd advice you to also consider the many mentions made in other answers to the law of Demeter: to expose action methods (that act on gun) instead of the entire gun object via a getter method. Since the soldier "has" the gun (it is in his hand and he pulls the trigger), it seems more natural to me that the other actors "ask" the soldier to fire. I know this may be tedious if gun has many methods to act on, but maybe also these could be grouped in more high-level actions that the soldier exposes.
Provide a "getGun()" or simply "gun()".
Imagine one day you may need to make that method more complex:
Gun* getGun() {
if (!out_of_bullets_) {
return &gun_;
} else {
PullPieceFromAnkle();
return &secret_gun_;
}
}
Also, you may want to provide a const accessor so people can use a const gun on a const soldier:
const Gun &getGun() const { return gun_; }
There's no golden rule that applies 100% of the time. It's really a judgement call depending on your needs.
It depends on how much functionality you want to hide/disallow for the gun from access to the Solider.
If you want to have only read only access to the Gun you could return a const reference to your own member.
If you want to expose only certain functionality you could make wrapper functions. If you don't want the user to try to change Gun settings through the Soldier then make wrapper functions.
Generally though, I see the Gun as it's own object and if you don't mind exposing all of Gun's functionality, and don't mind allow things to be changed through the Soldier object, just make it public.
You probably don't want a copy the gun so if you make a GetGun() method make sure that you aren't returning a copy of the gun.
If you want to keep your code simple then have the soldier responsible for dealing with the gun. Does your other code need to work with the gun directly? Or can a soldier always know how to work/reload his own gun?
Encapsulate the functions to provide a consistent UI even if you later change the logic. Naming conventions are up to you, but I normally don't use "getFoo()", but just "foo()" as accessors and "setFoo()" as setters.
return reference-to-const when you can (Effective C++ Item #3).
Prefer consts, enums, and inlines to using hard coded numbers (Item #4)
provide unique naming conventions for your private members to distinguish them from arguments
Use unsigned values where they make sense to move errors to compile time
When const values, like maximums, apply to an entire class. Make them static.
If you plan to inherit, make sure your destructors are virtual
initialize all members to sane defaults
This is how the classes look after that. CodePad
#include <iostream>
#include <string>
#include <stdint.h>
using namespace std;
class Gun
{
public:
Gun() : _bullets(0) {}
virtual ~Gun() {}
void fire() {cout << "bang bang" << endl; _bullets--;}
void load(const uint16_t bullets) {_bullets = bullets;}
const int bullets() const {return _bullets;}
static const uint16_t MAX_BULLETS = 17;
protected:
int _bullets;
};
class Soldier
{
public:
Soldier(const string &name, const Gun &gun) : _name(name), _gun(gun) {}
virtual ~Soldier() {}
const string& name() const;
Gun& gun() {return _gun;}
protected:
string _name;
Gun _gun;
};
int main (int argc, char const *argv[])
{
Gun gun; // initialize
string name("Foo");
Soldier soldier(name, gun);
soldier.gun().load(Gun::MAX_BULLETS);
for(size_t i = 0; i < Gun::MAX_BULLETS; ++i)
{
soldier.gun().fire();
cout << "I have " << soldier.gun().bullets() << " left!" << endl;
}
return 0;
}

a struct doesn't belong in an object oriented program

Or does it?
Should an object-oriented design use a language construct that exposes member data by default, if there is an equally useful construct that properly hides data members?
EDIT: One of the responders mentioned that if there's no invariant one can use a struct. That's an interesting observation: a struct is a data structure, i.e. it contains related data. If the data members in a struct are related isn't there's always an invariant?
In C++, structs and classes are identical except for the default public/privateness of their members. (This default is easily, and usually, overridden.)
However, most programmers think of a struct as a "data object" and a class as an "interactive object". That's not a bad thing; and in fact should be taken advantage of. If something is just an inanimate lump of data (even maybe if it has a couple of inspector methods), use a struct for it; it'll save a bit of effort when a programmer is trying to see what it's for.
Don't be a hiding zealot. If your get/set methods do nothing but simply copy verbatim the value onto/from a hidden, private field, you've gained nothing over a public member and only complicate unnecessarily your class (and, depending on the intelligence of the compiler, slow its usage a bit).
There's a case for not allowing direct access when your setter methods do some validation, copy the data somewhere else, process it a bit before storing it, etc. Same in the case of getters that actually calculate the value they return from multiple internal sources, and hide the way it's derived (I believe Bertrand Meyer speaks a bit about this in his book)
Or if allowing the users of your class to directly change such a value would have unintended side effects or breaks an assumption some of your member classes have about the values. On those situations, by all means, do hide your values.
For instance, for a simple "Point" class, that only holds a couple coordinates and colour, and methods to "Plot" it and "Hide" it on screen, I would see no point in not allowing the user to directly set the values for its fields.
In C# for example I use structs for some simple better-left-as-values data types:
public struct Point
{
int X;
int Y;
}
and for any P/Invoke to libraries where the arguments are structs you'll have to use them for certain.
Do they belong in the general design of an application? Of course they do, use a struct when it makes sense to do so. Just like you'd use a enum with bit flags when it makes sense to do so instead of resorting to some complicated string parsing for storing combined values.
In C++, the difference between a struct and a class is the default visibility of its contents (i.e. public for a struct, and private for a class). I guess this difference was to keep C compatibility.
But semantically, I guess this is subject to interpretation.
An example of struct
In a struct, everything is public (by default), meaning the user can modify each data value as desired, and still the struct remains a valid object. Example of struct:
struct CPoint
{
int x ;
int y ;
CPoint() : x(0), y(0) {}
int getDistanceFromOrigin() const
{
return std::sqrt(x * x + y * y) ;
}
} ;
inline CPoint operator + (const CPoint & lhs, const CPoint & rhs)
{
CPoint r(lhs) ;
r.x += rhs.x ;
r.y += rhs.y ;
return r ;
}
You can change the x value of a CPoint, and it still remains a valid CPoint.
Note that, unlike some believe, a C++ struct can (and should) have constructors, methods and non-member functions attached to its interface, as shown above.
An example of class
In a class, everything is private (by default), meaning the user can modify the data only through a well defined interface, because the class must keep its internals valid. Example of class:
class CString
{
public :
CString(const char * p) { /* etc. */ } ;
CString(const CString & p) { /* etc. */ } ;
const char * getString() const { return this->m_pString ; }
size_t getSize() const { return this->m_iSize ; }
void copy { /* code for string copy */ }
void concat { /* code for string concatenation */ }
private :
size_t m_iSize ;
char * m_pString ;
} ;
inline CString operator + (const CString & lhs, const CString & rhs)
{
CString r(lhs) ;
r.concat(rhs) ;
return r ;
}
You see that when you call concat, both the pointer could need reallocation (to increase its size), and the size of the string must be updated automatically. You can't let the user modify the string by hand, and forget updating the size.
So, the class must protect its internal, and be sure everything will be correctly updated when needed.
Conclusion
For me, the difference between a struct and a class is the dependencies between the aggregated data.
If each and every piece of data is independent from all the others, then perhaps you should consider a struct (i.e., a class with public data member).
If not, or if in doubt, use a class.
Now, of course, in C#, the struct and class are two different type of objects (i.e. value types for structs, and referenced types for classes). But this is out of this topic, I guess.
Technically, a struct is a class with the default visibility of public (a real class has a default visibility of private).
There is more of a distinction in common use.
A struct is normally just a collection of data, to be examined and processed by other code.
A class is normally more of a thing, maintaining some sort of control over its data, and with behavior specified by associated functions.
Typically, classes are more useful, but every so often there's uses for something like a C struct, and it's useful to have a notational difference to show it.
The matter is easy. If the class does have invariants to guarantee, you should never make the members constraining the invariant public.
If your struct is merely an aggregate of different objects, and doesn't have an invariant to hold, you are indeed free and encouraged to put its members public. That's the way std::pair<T, U> in C++ does it.
What's that invariant stuff?
Simple example: Consider you have a Point class whose x and y members must always be >= 0 . You can make an invariant stating
/* x >= 0 && y >= 0 for this classes' objects. */
If you now make those members public, clients could simply change x and y, and your invariant could break easily. If the members, however, are allowed to contain all possible values fitting their own invariants respectively, you could of course just make those members public: You wouldn't add any protection to them anyway.
A struct is essentially a model class but with different syntax.
public struct Point {
int x;
int y;
}
is logically the same as:
public class Point {
private int x;
private int y;
public void setX(int x) { this.x=x; }
public int getX(); { return x; }
public void setY(int y) { this.y=y; }
public int getY(); { return y; }
}
Both are a mutable model that holds pair of integer values called x and y. So I would say that it's a valid object oriented construct.
Yes. It's like a mini-class.
Yes, they do. They have different semantic than classes. A struct is generally considered and treated as a value type, while a class is generally considered and treated as a reference type. The difference is not as much pronunciated in every day programming; however, it is an imprtant difference when it comes to things like marshalling, COM interop and passing instances around.
I use structs regularly - mostly for data received from the network or hardware. They are usually wrapped in a class for use by higher level parts of the program.
My rule of thumb is a struct is always pure data, except for a constructor. Anything else is a class.
Most answers seem to be in favor of a struct as something to be acceptable and useful, as long as it does not have a behavior (i.e. methods). That seems fair enough.
However, you can never be sure that your object does not evolve into something that may need behavior, and hence some control over its data members. If you're lucky enough that you have control over all users of your struct, you can go over all uses of all data members. But what if you don't have access to all users?
A struct, as used in C or C++, and the struct used in C# ( or any .Net language ), are such different animals that they probably should not even have the same name... Just about any generalization about structs in one language can easily be false, or true for a completely unrelated reason, in the other.
If there is a need for invariant, make it a class. Otherwise, struct is OK.
See these similar questions:
When should you use a class vs a struct in C++?
What are the differences between struct and class in C++
plus:
According to Stroustrup in the C++ Programming Language:
Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures."
Formally, in C++ a struct is a class with the visibility of its members set to public by default. By tradition structs are used to group collection of homogeneous data that have no particular reasons for being accessed by specific methods.
The public visibility of its members makes structs preferred to class to implement policy classes and metafunctions.
There's nothing wrong with using structs per se, but if you're finding yourself needing them, you should ask what's wrong with your analysis. Consider, eg, the Point class above: it gives some little improvement in readability, since you can always use
Point foo;
//...
foo.x = bar;
in place of, say, having a two element array as in
#define X 0
#define Y 1
//...
foo[X] = bar;
But classes are meant to hide details behind a contract. If your Point is in some normalized space, the values may range in the half-open interval [0.0..1.0); if it's a screen they may range in [0..1023]. If you use a struct in place of accessors, how will you keep someone from assigning foo.x = 1023 when x should be everywhere < 1.0?
The only reason C++ programmers used structs for Points is that back at the dawn of time --- 20 years ago, when C++ was new --- inlining wasn't handled very well, so that foo.setX(1023) actually took more instructions than foo.x = 1023. That's no longer true.
Structs are fine as long as they're kept small. As you probably know, they are allocated on the stack (not the heap) so you need to watch the size. They can come in handy for small data structures like Point, Size, etc. A class is usually the better choice though, being a reference type and all.