This question already has answers here:
What are the differences between struct and class in C++?
(30 answers)
Closed 1 year ago.
In C++, I'm trying to decide whether or not to use a struct or class. So far I understand that both are more or less identical, but a class is used more often when private variables are needed or to group the concept of an object that performs actions.
But what I'm wondering is: Does including functions within a class increase the memory requirements (as opposed to having structs, with functions separated)?
Here is an example
class Vector2D {
public:
int x;
int y;
Vector2D();
getMagnitude();
Normalize();
}
vs.
struct Vector2D {
int x;
int y;
}
// Some functions defined separately
getMagnitude(Vector2D v);
Normalize(Vector2D v);
And if I have a bunch of other vector functions, say, adding two of them together and I have a vector class, is it better if those are included in the class, so you have a function like addToVector(Vector2D v2) or to keep these multi vector functions outside of the class so that you'd have an addToVector(Vector2D v, Vector2D v2)?
I understand the second question might lean towards opinion, but if there is a "best practice" defined way, I'd like to know.
Thank you
C++ Efficiency of Classes vs Structs
Structs are classes. There is zero efficiency between one and the other.
Does including functions within a class increase the memory requirements (as opposed to having structs, with functions separated)?
No. There is no practical difference between "memory requirements" of member functions and non-member functions.
Also, structs can have member functions. All classes can have member functions, and structs are classes.
Related
This question already has answers here:
When should you use a class vs a struct in C++? [duplicate]
(27 answers)
Closed 1 year ago.
I have basic knowledge of structures from C, and as far as I'm aware, classes and structs are not exactly the same, but the c++ primer defines a "class" using the struct keyword starting on p. 72-73. Here's a small excerpt with the code:
"Defining the Sales_data Type
Although we can’t yet write our Sales_item class, we can write a more concrete class that groups the same data elements. Our strategy for using this class is that users will be able to access the data elements directly and must implement needed operations for themselves.Because our data structure does not support any operations, we’ll name our version Sales_data to distinguish it from Sales_item. We’ll define our class as follows:"
struct Sales_data {
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
This book is suppose to be an authoritative overview of C++11, so why would they use the keyword struct instead of class to describe a class type?
It's common use to define POD types as struct and data types which contain other members, constructors, methods, etc. as class. They are basically the same, the difference being the members are public by default in a struct and private by default in a class.
The usage in the book is consistent with the above description.
This question already has answers here:
How Non-Member Functions Improve Encapsulation
(8 answers)
Closed 5 years ago.
The C++ Core Guidelines section C.4 recommends "make a function a member only if it needs direct access to the representation of a class", using the following example:
class Date {
// ... relatively small interface ...
};
// helper functions:
Date next_weekday(Date);
bool operator==(Date, Date);
I don't understand the reasoning here. In my opinion this would be a better option:
class Date {
// ... relatively small interface ...
Date next_weekday(Date const&) const;
bool operator==(Date const&) const;
};
What is the advantage in this reasoning?
Member functions have access to private members of a class. This means that they can use the internal representation of the class in their logic.
Non-member functions only have access to public members of a class. This means that they can only use the publicly exposed interface of the class, thus improving encapsulation.
It increases encapsulation
When you change the private implementation of Date, you only have to check // ... relatively small interface ... for places where previous assumptions may no longer hold, instead of // ... relatively small interface ... + next_weekday + operator== + ...
This question already has answers here:
Where are member functions stored for an object?
(2 answers)
Closed 7 years ago.
In C++, if I define a function like below
int func1(int a, int b){
int res;
// do some stuff for a, b, res;
return res;
}
I know there will be only one copy of machine code for func1 generated by the compiler if it is not inlined (correct me if I am wrong), and during program execution every call for func1 will call that copy of machine code. However, for member functions in class, like below
class A{
private:
// some data members and member functions
public: // or alternatively private:
int func2(int a, int b){
int res;
// do some stuff for a, b, res;
return res;
}
}
I have some questions as below:
If I do sizeof(A), it only returns the size of the data members (possibly including padding bytes), then where func2 is stored? Is func2 stored in a piece of memory continuous with the data members? If not, doesn't it penalize caching?
If I declare std::vector<A> v(1000), will there be 1000 copies of machine code for func2 generated? If yes, I think this will result in a big memory wastage and performance disadvantage compared to declaring functions outside the class like func1(correct me if I am wrong).
In C++, class member functions are implemented in essentially the same way as regular C-style functions. However, they have a "secret" first argument which is the this pointer, to the instance of the class on which the method was called. Thus, there is only one copy of the class member function instantiated either.
(There are some potential issues about multiple compilation units and linkage... but since you ignored them in the question we'll keep ignoring them now for convenience.)
If you want to see for yourself, you can take pointers to the member functions of various instances of a class, and compare them to see if they are equal or not.
This question already has answers here:
What are the differences between struct and class in C++?
(30 answers)
Closed 7 years ago.
I read that the main difference between a class and a structure is that class is reference type and structure is value type.
can anybody explain me what does the value type and reference type means...?
You must be thinking of a different language. In C++, class types are semantically the same whether you introduce them with the class or struct keyword. They are object types (which one might loosely call "value types"), in the sense of being objects with a value representation.
The only difference is that base classes and members are public by default if you use struct, and private if you use class.
Reference types are denoted with & or &&, and can refer to any object or function type, not just classes.
The only difference between classes and structs is that by default members/bases are private to a class but public to a struct.
Now values and references are totally orthogonal concepts in C++ to class/struct, basically meaning instance of a class/struct and handle-to-instance.
In c++, the only differences between a struct and a class is the default member access and default inheritance:
struct A : BaseClassOrStruct { // public inheritance
int member; // public member
}
class A : BaseClassOrStruct { // private inheritance
int member; // private member
}
However, I usually do make a distinction between them: I use a struct to indicate that my objects really are just a collection of data members (that typically have public access) without methods (other than setters and getters).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In C++, which of these ways is better?
// this is class, not a struct (just means members are public by default)
struct foo {
int w, h;
private:
public:
};
Or
class foo {
private:
int w, h;
public:
int getW() { return w; }
int getH() { return h; }
};
In this case:
foo *A;
If I'm trying to get the values of w and h,
should I use A->w and A->h for the first example or A->getW() and A->getH() for the second example?
Right now I'm using the first example, but is it in any way better practice to make methods to return the private variables? Is there some advantage to one way over the other?
If this is your only concern, then there is no practical difference. If you intend to only have members that are visible to the outside via accessor methods, then they might as well be made public (or a POD.) For example:
struct SomeSortOfInformation
{
int w, h, x, y, pixelFormat, whatever;
};
If you intend to protect implementation details, or to change the behavior of accessing a variable (i.e., this is a common idiom in C#), then feel free to use accessor methods.
void setWidth(const int& w) {
if (w <= 0) this->w = 0;
else this->w = w;
}
The immediate difference is that users of the class can assign to the values of w and h in the first example, but not the second.
The difference for future code changes is that the author of the class can change the way that foo's data is stored in the second example, but not the first. For example if the class represents a rectangle, then you could switch to storing the co-ordinates of the corners, and calculate the width and height when requested.
There is no certain way that is "better". If you have a class that is defined to be a dumb data container, that users can read from and write to, and it is guaranteed that it will not in future perform any clever calculations, then you can use public data members. An example of this in the standard libraries is std::pair, which has public data members first and second. Many OOP programmers will (on principle) never define or document any such guarantee, but the designers of the C++ standard libraries do not agree with this absolute principle. In any case C++ is not designed on strict OOP principles.
If you have a class that just so happens to store values that are useful to the user, but is not guaranteed to store them as members, then you would use accessors if necessary. An example in the standard libraries is std:vector, which has functions begin() and end(). In some implementations of vector they just return the values of two private data members, in other implementations they do something else.
If possible, though, give the class the functionality that the user needs, so that they don't need public data or accessors. An example in the standard libraries is std::stack, which has a protected data member for use by derived classes, but does not give "normal" users any direct access to it. If you find yourself routinely writing accessors for most data members of most classes you write, then you should seriously consider whether your design can be improved. Accessors mean that users of your class must provide the logic to use the data member. But the main advantage of classes is the ability to keep the logic for using data in the same place that the data is defined. If users always provide the logic then you're not using that opportunity.
By the way, there are a couple of errors in your question:
this is class, not a struct
It is a struct. It is also a class type.
int getW() { return w; }
Getters should be const functions: int getW() const { return w; }