Accessing class members in c++ [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 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

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

Is it possible in C++ to make an instance of a class as a member of structure? [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 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"

Are there advantages to using namespaces over classes? [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
It seems that classes provide a scope for variables and functions, essentially letting it do everything namespaces do.
Am I wrong about this?
If not, why are namespaces used over classes?
You can't specialize templates in class scope for one, among many.
class C
{
template<typename> struct S;
template<> struct S<int> {}; // error
};
More importantly, usage of language features indicates meaning, using something familiar and easy to understand has value on its own.
If you have a class which consist of static member functions only, they appear very similar to namespaces
class A {
static void foo();
}
can be used A::foo();
If you use a namespace
namespace B {
void bar();
}
this will also be used as B::bar();
Classes and namespaces both are uniquely defining the name of a function (see name mangling).
Now, the similarities are done. Classes are the fundamental organisation unit in object oriented programming. They encapsulate data and logic operating on this data and hide everything (e.g. it's data and private methods) which is not crucial for the user of the class.
One very important property of a class is, that you create objects form it. Normally you create several objects form one class. This cannot be done with namespaces.
It's two different purposes.
A namespace is there to avoid naming conflicts, to hide some names to the outside world, and eventually to help in assembling components (when namespace and their aliases are used to address different libraries, e.g boost::regex vs. std::regex).
A class is there to be instantiated and create objects. A variable in a namespace exists only once. A non static data member in a class exists once for each instantiated object. So it's more than just encapsulation and access control.

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

Class of std::vector vs non-member functions (along with a typedef) [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 7 years ago.
Improve this question
I have the following design dilemma in my project:
I have objects of a class I've designed stored within a std::vector.
I would like to add some methods for this kind of vector (std::vector<MyClass>).
I'm thinking of encapsulating this vector in another class and add these methods which I need and of course provide all the functionality of std::vector which I use. Is this a wise idea? or should I just use non-member functions and maybe a typedef for my own convenient?
Non-member functions are the right thing in this instance. See Scott Meyer's article on the topic How Non-Member Functions Improve Encapsulation.
Also, please do use typedef std::vector<MyClass> someTypeName; You don't want std::vector<MyClass> littered throughout your code. You want what the type is not how it's implemented. If you ever have to change the implementation to use a different container, you will be quite glad you used a typedef.
ETA: in comments I am reminded of using and its superiority to typedef.
using someTypeName = std::vector<MyClass>;
You should use typedef only if your type is really meant to be a vector. A typedef gives you very little control on how your own type behaves and what you can do with it.
If not, and if you want a proper long living design, then you should hide the implementation details:
What if tomorrow you use another standard container like a list or a map ?
What if your requirements evolve and you need some non standard structures like concurrent_vectors or even a database ?
What if at insertion or other vetor operation, you decide to do some additional steps.
Two ways of doing it:
having a vector member and publish only the methods that you really need (according to the principle of composition rather than inheritance)
inheriting from the standard vector, but again, ONLY IF your type represents a vector structure, AND IF you're aware of the limitations (e.g absence of virtual destructor, etc..) and their consequences.
If I understand you correctly, you want to have a custom container that provides both std::vector member functions and custom functions specific to that container?
IMO, the most adapted way in your case is to create your own type and encapsulate your vector:
class MyClass{};
class MyContainer {
using size_type = std::vector<MyClass>::size_type;
public:
MyContainer() = default;
MyContainer(std::vector<MyClass> const& vec) : vec_(vec) {}
size_type size() const noexcept;
// other functions you want
private:
std::vector<MyClass> vec_;
};
Other "bad" options are :
Create non-member functions, but it is not adapted to OOP design
Inherit from std::vector, but STL classes are not designed for
inheritance
Hope it will help you.