Is it possible in C++ to make an instance of a class as a member of structure? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
struct Frame {
int frame_num;
BoundingBox bbox;
};
In this above structure, BoundingBox is a class and later used in the following way. What is the benefit of making a class instance as a member of a structure?

Is it possible in C++ to make an instance of a class as a member of structure?
You've answered your own question in your snippet. Yes, possible.
what is the benefit of making a class instance as a member of a structure?
What is the benefit of int frame_num in Frame? It's the same benefit you get in having custom types.
Classes are a way of making custom types (BoundingBox in your example) which work besides the built-in types (int, float, etc.) the language gives out of the box. Both can be put inside another custom type (like Frame) and they provide a way to interact with data. E.g. int is a type that allows the programmer to work with integer data in a specified way i.e. int dictates how the values of its type interact with say float. Likewise, a custom type will allow the user of the type to work with some data is some fashion.
Aside: Classes and structs are almost the same in C++.

It's perfectly fine. Go ahead and use it.
The two abstractions -- Frame and BoundingBox -- server their own purposes. Whether one is a class and the other is a struct does not change that.

In essence, structures are almost identical to classes.
However, members of a struct are declared as public by default, while members of a class are declared as private ones.

Why not? A struct is a class so there is nothing special about them.
It's called "Object Association", and it depends on the design. Typically, object association is called the "Has-A" relationship.

In C++ Class and Struct are the Same thing, with minor difference of the default access modifier being private for class and public for structs
Additionally, syntax speaking nesting those constructs is allowed if not required inorder to get correct OOP design.
That said, I'd note that, semantically, there is a difference:
as structs are mostly used to describe data,
while classes mostly describe object.
Some programmers might (allow themselves to) use memset on a struct, or copy it to another memory location.
These operations might corrupt the class like struct by:
- corrupting vptr of the contained class member
- If this struct has a virtual method itself then it's own vptr.
- Copy pointers and create some surprising results.
Bottom Line:
Nest classes in classes, structs in classes...
But avoid nesting class in struct, there is no good reason to do so.
Also, You might want to embrace the convention of "struct -> DATA, class -> Object"

Related

C++: same method, different classes, can't be virtual or inherited [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
Let's say I have three very different classes with no common parent: Camera, Light, Model.
But all three have the same generic SetPos(float x, float y, float z) method that translates their position in 3D space.
I also have a reference list (e.g. std::map) that stores pointers to objects of all three classes of type void* - meaning it's generic and non-descript.
So to summarize: I have a bunch of cameras, lights and models with very different data structures that all can be moved around using SetPos method that each have and I keep generic, no-type void* pointers to all of them in a single map for quick access.
What I want to know is if it's possible to somehow call that SetPos from a void* without determining class object type (e.g. storing it in that std::map and then casting that void* to a proper class pointer using it)?
Is there some template idea for it?
Or should I just create a generic interface class that will have a pure virtual method SetPos(x,y,z) and simply make those three classes inherit from it - and be done with it by simply casting that pointer to that single class - but I'd rather avoid this option because... reasons and what if some alternative way is better?
Yes there is a template for this, use std::variant instead of void*. I guess your code contains some dynamic casts or worse already to interact with the stored objects. That is bad design in general, type system is our friend, types should not be erased lightly.
Then you can do something akin to this:
std::variant<A,B,C> obj;
...
std::visit(obj,[&](auto& o){o.SetPos(x,y,z);};

(C++) Finding the child type of a base type pointer [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a class Base and 4 classes A, B, C, D, each derived from Base. I'm passing a pointer Base* to a function.
I know I can use the dynamic_cast to check for each separate child type. In order to find out which type that pointer is, I have to use 4 if statements which isn't practical.
Can this be done in some other, more elegant way?
Or should I hold a const int variable in each subclass indicating its type to simple call GetType()?
Or should I focus on making sure that when I have a storage - for example an inventory and A, B, C, D are different types of items - the items sort themselves (so that when I have 4 lists, the new item is placing itself on the proper list instead of having a function managing the inventory, checking for the type of the item and then placing it on the right list)?
Or should I hold a const int variable in each subclass indicating its type to simple call GetType()? Or should I focus on making sure that when I have a storage - for example an inventory and A, B, C, D are different types of items - the items sort themselves (so that when I have 4 lists, the new item is placing itself on the proper list instead of having a function managing the inventory, checking for the type of the item and then placing it on the right list)?
Neither one. You should properly design interface of the base class so when you use pointer to the base class you do not need to know what actual type it is, you just use interface. It is difficult to give you more details as there is no enough information in your question.
Note: using dynamic_cast directly or having function that simulates it (returning enum from virtual function that gives you particular type for example) is almost always a sign of improper design, though sometimes you may use that shortcut due to some technical reasons. But designing your app and thinking how you detect actual type from start - definitely wrong approach to OO design.
Note2: I assumed that you are doing object oriented design due to using inheritance and virtual functions. Though C++ is a multi-paradigm language and you can solve your issue different way. For example you can have std::variant with types A, B, C and D enumerated and use visitor to deal with each type individually or generically with a template function. But this is different approach than OOD and your classes may not need common base in this case at all. Of course you can mix them together but usually that does not lead to good design. When you mix different paradigms you get worst from each of them.

Accessing class members in c++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I got back coding in C++ after a long while and was wondering if there is a way to access data member of a class quickly for manipulation.
Assume a case where you have like 10 data members in a class which overloads a bunch of operators (thought of this while overloading operator=). Now you would want to add/subtract a few data members to the class.
Is there a generic way to accomplish this without having to go to individual functions and change them? I'm thinking of a possibility of running through all the members of a class in a kind of loop construct.
As there is no built-in reflection in C++ (yet), you have to list all your members somewhere. One way to save you from doing this over and over again is to define a for_each_member method which passes every member to some functor:
template <class F>
void for_each_member(F f);
Now you can easily apply arbitrary operations to all your members, and you only have to maintain one listing of members per class.
Running example: http://coliru.stacked-crooked.com/a/c813fc73c5519ee0
If you want to perform different actions for different subsets of member, you have to find a way to separate these apart. You could do this by type (as shown in the example) or you could additionally pass some kind of identifier to your functor in for_each_member.
Here I use a macro to pass both the member and its name to the functor: http://coliru.stacked-crooked.com/a/5a59c027e25c33fb
I'm thinking of a possibility of running through all the members of a class in a kind of loop construct.
No, such isn't possible in general, since standard C++ doesn't have any runtime reflection mechanism, that allows you to access class members by symbolic information.
What you can do of course is something to keep your class member variable values in a kind of std::map<std::string,T> dictionary, and access these with symbolic keys (replacing the actual class member variables of course).
But that would require the value type to be
all of the same type
something like std::experimental::any

Public variables bad practice vs Getters and Setters functions? [closed]

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 7 years ago.
Improve this question
I came across this during his stream, and this stuck out to me like a sore thumb since. I thought maybe if I saved the video and come back to it in the future when I'm more proficient I'll understand it, but it just kept on bothering to just leave it be. Here's the video...
It automatically starts at 1:13:00 for you.
https://youtu.be/uHSLHvWFkto?t=4380
As a new programmer to C/C++ after hearing this its completely warped my way of thinking. With him being a professional and all I should take the advice, but I need some clarity. From sites, videos, to books, I've read that the use of public variables is a bad practice, but from what I'm getting from this video its saying otherwise. In the video he's uses a struct which by default has a access modifier of "public" vs a class which has a default access of "private". Is there something I'm not comprehending properly here.
I don't know what to do. If I make my variables public won't I risk ambiguity ? The way he's saying that he'll automatically fire someone for coding in format is getting to me haha! Which one should I truly use ? When and Why ?
In my experience people use getters/setters excessively for no good reason.
One can think of two major kinds of classes: the ones grouping together related data and the others providing behaviour.
Behaviour classes must be encapsulated with no public data members.
Data classes normally should have data members public and no behavior.
The grey area between these two is mutable data classes with invariants or dependencies between members, e.g. if member a is 1, then member b must be in range [1-10]. For such cases usage of getters/setters may be justified. For immutable data classes the constructor must establish the invariant.
First of all, a struct is completely equivalent to a class, but with the default member access being public rather than private.
Now, in Object Oriented Programming (OOP), it's not considered good practice to have public data members (variables), because that makes all your code dependent on the internals of the class, and thus breaking a primordial principle of OOP, and that is...
Holy and Sacred Encapsulation
Encapsulation is the coding philosophy that states that a class should englobe both data and the code that manages it in a single tight entity. That is, you don't access data directy, but rather you use methods from the class to manipulate such data. This has several design advantages, such as that you'll know that no code except the one inside the class may incorporate bugs with respect to the manipulation of such information.
Now, get()ers and set()ers, otherwise known as accessors, are a complete lie! With accessors, you're tricking yourself into thinking that you're respecting encapsulation, when you're rather breaking it! It adds bloat, unnecessary verbosity, bugs, and everything but encapsulation. Instead of having a class Person with unsigned getAge() and void setAge(unsigned), have it with a unsigned getAge() and a void incrementAge() or however you want to call it.
Now, to your question's core...
"Plain old" structs
Encapsulation is not always desired. Although you should (usually) not do this on header files (again, for at least some bit of encapsulation), you may create static plain old structs that are private to a single translation unit. My recommendation is to make them even "older" than they already are, i.e...
All data members are public.
No methods.
No constructors (except implicit ones).
Inheritance is always public, and only allowed from other plain old structs.
I repeat, don't put them on header files!
Now, another use for plain old structs is (ironically) metaprogrammatic exporting of constexpr data and types, otherwise known as modern-hardcore-template-metaprogramming-without-having-to-type-public-everywhere, for example...
template<bool B, typename T>
struct EnableIf {};
template<typename T>
struct EnableIf<true, T> {
typedef T type;
};
template<bool B, typename T>
using SFINAE = typename EnableIf<B, T>::Type;
It's certainly difficult to control the internal consistency of your object if you make the data members public.
What works well is to use constructors to set up the state of an object, then use public functions to retrieve values of member variables, but only if that's needed. If you need to mutate the object after construction, then provide very specific methods for that purpose.
If, however, your object is no more than something that aggregates orthogonal data types, then use public access for all members: a struct works well for that.
Note that the only difference between a struct and a class is that in the former, the default access is public whereas in the latter it is private.
If you keep your data members private then you can easily control about accessing their value. For example you have age variable in your code.
public:
int age;
Now someone outside your class can easily change value of age, may also assign illegal value, for example age = -10. But your logic suggests age cannot be negative, so best practice is to keep variable private, and give some function which will assign value to your variable.
private:
int age;
public:
void setAge(int age)
{
if (age > 0)
this->age = age;
}

Why do we need a `class` in C++, when a `struct` can be used to achieve the same? [closed]

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 9 years ago.
Improve this question
Using a struct we can achieve all the functionality of a class: constructors (that can be modified/overloaded), destructors (that can be modified/overloaded), operator overloading, instance methods, static methods, public/private/protected fields/methods.
Why do we need class then?
Note: I don't want the answer saying that in struct, fields/methods are public by default.
You don't need classes, the language just gives you another option to choose from. Technically, you're right, you can achieve anything a class can do with a struct.
Besides the default access level, there's also the meaning most programmers associate with the two - struct generally means a light-weight, typically POD, data-type with little to no functionality. A class is usually associated with something bigger.
As Tal Pressman answered at When should you use a class vs a struct in C++?:
From the C++ FAQ:
The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults.
struct and class are otherwise functionally equivalent.
OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.
http://www.parashift.com/c++-faq-lite/classes-and-objects.html#faq-7.8
I think one addition to this reason could be that C already had structs. When Bjarne Stroustrup designed C++, he wanted to add classes with all the functionalities you listed in your original question, features which were not present in C. When implementing those features, he probably realised it didn't make sense to make two separate implementations for struct and class (except the public/private default visibility).
TL/DR: in C++ structs/classes describe the intent of the programmer to have POD or more complex abstractions, and the introduction of the class keyword is probably here for historical reasons (add an additional keyword in order to create featurefull classes, then backport those features into the struct keyword because it's more pragmatic to implement).
class is simply the commonly accepted name in OO for a type used for instantiating objects. When introducing the OO paradigm in C++, it was deemed less surprising to use class instead of struct.
struct was kept to maximize backwards compatibility with C.
Today's usage of the two is in line with this : struct is most commonly used for C-style POD types, while class is used for the OO concept of classes.
To make a long story short, class really wasn't needed at all. It changes the defaults to ones that are arguably safer and more applicable to OO programming, but you could use a struct (as defined by C++) for any place that you currently use a class (if you wanted to get cute and meta about it, you could call struct a base class of class that satisfies the LSP).
At the same time, misunderstanding of struct in C++ is rampant, and class fits the intended concept enough better that it's often much easier to explain. New users often seem to find it at least marginally more understandable -- a reasonable goal in itself.
There are no such difference between C++ struct and C++ class, you can perform almost all the functions with struct as you can do with class, but struct is a C keyword which gradually got modified/evolved in C++ and named as class. A we are in C++, it is better to use class rather than struct.
Take an example, if you have done some coding in C++ and some person who works in Java came after 2 months to review your code, which one will he find comfortable to understand a code with "struct" or a code with "class"?