Hi all,
I wanted to share a bit of a personal eureka moment I had yesterday, I'm still trying to get to grips with the language and I've been making progress in understanding nuanced concepts like invariance, something clicked for me yesterday when I was doing a practice exercise which I'm super excited to share, it might be a bit embarrassing..... I feel like a kid learning to ride a bike.
This isn't a question per se or me asking for help..... its more of a Look Ma No Hands moment for me.
I've been trying to understand the difference between a struct and a class in C++ since before the holidays. I know that the core difference is a Structs access specifier defaults to public and a class defaults to private, but the rabbit hole I went down was when to use a struct over a class.
I worked through an example I found on Planet-Source-Code the example was a program that asks the user for five positive integers and adds them together. The original code used a class with public data members, but it dawned on me that this could be better implemented as a struct, which is just a bundle of data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <iostream>
using namespace std;
struct Adder
{
// Data Members
int num1;
int num2;
int num3;
int num4;
int num5;
// Member Functions
// Usually I would separate the interface from the implementation but
// this is too small of an example to warrant that.
int addTogether(int num1, int num2, int num3,
int num4, int num5)
{
return(num1 + num2 + num3 + num4 + num5);
}
};
|
What I realised in the general sense of my understanding of the concept was that there is no real invariance with the data members, all the values (numbers) are subject to change because they are going to be added together,
and the data members in this context don't need to be private, these are the two main considerations I feel are what determines in general if you choose a struct over a class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
int main()
{
// Instance Variable(s)
Adder values;
cout << "\n\t Welcome to 5 Number Adder ";
cout << "\n\n";
cout << "Please Enter 5 positive integers: ";
cin >> values.num1 >> values.num2 >> values.num3 >> values.num4
>> values.num5;
cout << endl;
cout << "The total sum = " << values.addTogether(values.num1,
values.num2,
values.num3,
values.num4,
values.num5) << ".";
cout << endl;
return 0;
}
|
I just want to ask if this makes sense and if I'm on the right track conceptually with how I've understood invariance and how I've formulated my two considerations for using a struct or a class? I am eager to learn and understand more.
Thanks