I want to have 1 class that holds all objects to my other classes.
So for example: If player class want a member of enemy class, I want to access the enemy class using that 1 class.
An example:
class objectHolder{
public:
enemyClass enemy;
};
class enemyClass{
public:
void member();
};
class player{
public:
objectHolder oh;
oh.enemy.member(); //I KNOW THIS IS ILLEGAL BUT I NEED SOMETHING LIKE THIS
};
I know the code is incorrect and does not compile well, but I hope you get the idea. Does anyone know how to actually do this? Because I actually need 1 class that all classes can access. Every class can call getters and setters and stuff from other classes by using that 1 big class.
I hope I was clear enough, thanks in advance.
You can not call function in class body ... try this code may useful
class enemyClass{
public:
void member(){std::cout<<"Test";}
};
class objectHolder{
public:
enemyClass enemy;
enemyClass getEnemy(){return enemy;}
};
class player{
public:
objectHolder oh;
void getresult(){oh.getob().member();}
};
int main()
{
player p;
p.getresult();
}
oh.enemy.member(); is a perfectly legal C++ statement since all members involved have public access. Where you've put it makes no sense however since statements can only appear in a function body.
1) Make a singleton
2) Initialize it & include all objects you want to hold.
3) Access the singleton instance from anywhere you please.
4) Realize that this is a horrible way to structure your program.
Related
I have this large class that I want to separate into different classes. The reason why it was large because the class had many private variables and functions that are needed to run the program. I was tired of scrolling down the 1000+ lines of code trying to add or edit code. I am wondering if it is possible for the classes to interact with one base class that includes all the private/protected variables it needed to operate, or simply have them as global variables.
I am aware of inheritance as I tried having the separate classes be derived from the base class, by doing something similar to this:
#include <iostream>
class Base {
public:
void sayPrivateVar() {
std::cout << privateVar;
}
protected:
std::string privateVar = "I am a protected variable!";
};
class Derived : public Base {
public:
void manip() {
base->privateVar = "That was updated from a derived class";
}
private:
Base* base;
};
int main() {
Base base;
Derived derived;
derived.manip();
base.sayPrivateVar();
return 0;
}
EDIT: Without creating another object inside a class.
it depends on your class and what you have in it. It is often better not have inheritance because derived classes may then get member variables that they don't need. There are a few other ways you can do. One way would be to group you private variables in different classes and then have member variables in the first class.
E.g.
class X {
int x;
int y;
int angle;
...
};
becomes
class XYVector;
class X {
XYVector v;
};
class XYVector
{
int x;
int y;
int angle;
};
You can continue in this direction and instead of making them concrete class like XYVector above have them as interfaces : to have it more elaborate and flexible check out https://en.wikipedia.org/wiki/Composition_over_inheritance
At any rate: avoid having globally declared variables.
This is a good question and the answer is absolutely. Inheritance is actually a very good solution in this particular context since that is how object code shares it's scope with other classes. One important thing to note here is that how you call your derived class is important because the inherited scope is set along with the derived class (i.e. declaring it public base would inherit the public and protected methods as opposed to declaring it private which would give the derived class even more access!)
so i have a user class which has two subclasses: manager and regular_User and i want manager to be singleton.
can anybody help me how to do it?
thanks!
class user{
public:
//sth
protected:
//sth
};
class manager:public user{ //i want this to be singleton
//
};
class regular_user:public user{
};
Although I question why you'd want manager to be a singleton, you could achieve something by using an anonymous class (or struct) with a single instance:
struct user {
static struct {
} manager;
};
The fun bit is allocating storage for the anonymous struct, since you don't know its type! You need to do this otherwise you'll get link-time errors. But C++11 has a way. Include
namespace {
decltype(user::manager) user::manager;
}
in exactly one compilation unit.
First of all, to make the class Manager a subclass of class User, you need to declare it with something like class Manager : public User. Then to make class Manager a Singleton class, you need to guarantee that only one instance of that class (one object) can be created. If you make all of its class member variables and member functions static, then those members will only get created once.
guys, I encountered this problem on a tech blog,the question asked what are the correct solution to resolve the compiler error generated in the below code. I have searched for hours and can not get an answer.
class SomeClass
{
public:
int data;
protected:
class Nest
{
public:
int nested;
};
public:
static Nest* createNest(){return new Nest;}
};
void use_someclass()
{
SomeClass::Nest* nst = SomeClass::createNest();
nst->nested = 5;
}
A. Make function void use_someclass() a friend of class SomeClass.
B. Make the function createNest() a non-static function of SomeClass.
C. Declare the class Nest in public scope of class SomeClass.
D. Make the object nst a reference object, and make the function
createNest() return a Nest&.
E. Derive a class from SomeClass. Make the object nst a derived class
pointer so that it can access SomeClass's protected declarations.
C is certainly right and trival.
I believe A is also right, and espectially E is a classic way of doing this kind of things.
I want implement what is said in E, but have a few difficulites. (I hope someone can also implement the idea in A), below is my code:
class derived:public SomeClass{};
void use_someclass()
{
derived::Nest *nst=SomeClass::createNest();
nst->nested = 5;
}
in the above, the idea is we can access the Nest definition from a derived class.
in function use_someclass(), in the first line, the right hand side is a static function, and returns type Nest*, but on the left hand side, I don't know how to match the right hand side type. "derived::Nest" is wrong. compiler error: can not access protected member. Nest is only a definition in SomeClass, not member.
what can we use to replace "derived::Nest"? derived certainly saw the definition of Nest, but I don't know how to "say" it. Maybe somehow via "this" pointer.
You can change the visibility in your derived class:
class derived : public SomeClass {
public:
using SomeClass::Nest;
}
I have a scenario where I've made a class, call it myClass, and I've realized I need another class, call it myOtherClass, which will be used inside of myClass but not outside of it. I haven't taken a Computer Science class for years, so I can't remember the terminology for what I'm trying to get at. There is no inheritance going on; just that myClass uses myOtherClass, in fact builds a tree of myOtherClass objects, and I want to encapsulate everything properly.
What is the concept I need to be following and what is it in C++ specifically? Please let me know if I need to try and make this question more clear.
It's called a nested class.
class myClass
{
class myOtherClass {...}; // myOtherClass is a nested class inside
// myClass.
myOtherClass a; // a is member variable of myClass.
// Its type is myOtherClass.
};
Sounds like composition. The class owns a private member:
class Edible {};
class Food
{
private:
Edible eds;
};
Note that this is in some ways similar to private inheritance (although as you mention you're building a tree of them, composition is what you want).
MyClass is composed of a tree of MyOtherClass objects. The design pattern is one of composition. If you implemented a templated Tree class, your code might look like this:
#include "MyOtherClass.h"
class MyClass
{
public:
MyClass();
~MyClass();
private:
Tree<MyOtherClass> m_tree;
};
Earlier, I asked a question on how to call a static member's member functions so as to initialize it before making actual use of the static object. Then, I realized that I was perhaps making use of the static member in a wrong way, which led to this question:
Given a particular class, MyClass, in how many ways can we design our code so that MyClass can gain access to the member functions of another class, YourClass? [N.B. Assume a generic situation where MyClass is declared in MyClass.h and defined in MyClass.cpp, and similarly for YourClass.]
I can think of a few, but being far from an expert, I guess you could name several others:
Containment: This can come in several 'flavors', with direct containment of a YourClass object being one option, while containing a pointer or reference to the object being another option:
class MyClass
{
public:
// Some MyClass members...
private:
YourClass instance; // or YourClass* instance / YourClass& instance;
// Some other MyClass members...
};
a) Of course, direct containment is convenient, but I can think of one immediate drawback: if YourClass is a bit hefty in terms of memory requirement, and you have several MyClass instances (as in my linked question), containing the object directly will be out of the question. Besides, the has-a relationship does not always make sense.
b) Having a pointer or a reference to the object might make better sense in that case. Using a reference has the problem that you might end up referring to an object which does not exist anymore, so you have to make sure that the YourClass object exists for the duration of the existence of the MyClass object.
c) In the case of a pointer, the problem above still exists, but you can more easily reassign the pointer to a new object.
Inheritance: One can inherit from the YourClass object, so that the members are inherited, such as:
class MyClass : public YourClass
{
public:
// Some MyClass members...
private:
// Some other MyClass members...
};
a) This is also very simple to set up for a few classes, but may become unwieldy for general use. For example, if YourClass was a random number generator, it wouldn't necessarily make sense to say MyClass is-a random number generator. One can of course define a wrapper class for the random number generator, say call it Randomizable and then MyClass could inherit from Randomizable, which makes good sense.
I would personally like to know more about the pros and cons of static members, global objects, singletons, and how they are correctly used. So, from a 'meta' point of view, what other methods or patterns would work?
PS. Though I'm asking from a C++ perspective, I guess the same could be said to apply for many other object oriented languages, so don't worry about giving examples in other languages.
There are basics about C++ class membership access.
You can access a member of your own direct class (public, protected or private)
class Foo {
public:
int fooMember;
};
int main() {
Foo foo;
foo.fooMember = 1;
}
You can access protect and public members of your parent class within the child class, and then depending on the inheritance indicator in the child class declaration the members of the parent are passed on to public, next-child, or kept private
class Animal {
protected:
int feet;
int age;
public:
enum color { blue, red, green, pink } color;
Animal(int feet) { this->feet = feet; }
bool getFeet() { return feet; }
void setAge(int a) { age = a; }
};
class Elephant: public Animal {
public:
Elephant(void):Animal(4) { }
int hasFeet(void) { return (feet > 0); }
};
// Here you can override stuff too so:
class Fish: protected Animal {
public:
int teeth;
enum Type { freshWater, saltWater } type;
Fish(void):Animal(0) { }
};
class Mackerel: private Fish {
public:
Mackerel(): Fish() { teeth = 12; } /* compiles */
};
class SubMackerel: public Mackerel {
public:
SubMackerel() { teeth = 8; } /* does not compile teeth not accessible here */
} ;
int main() {
Elephant pink;
Fish fishy;
Mackerel mack;
pink.color = Animal::blue;
// this won't compile since color is protected in Fish
// fishy.color = green;
fishy.type = freshWater;
// mack.type = saltWater; // will fail
}
the last way is to declare friends. A friend class can access all public and private members of the class it is a friend to.
Well this should be a start... You can read more about it
I have been looking for the answer about the kind of same thing , and landed here.
Buy anyway , atleast I should tell you what till now I have learned about this problem.
Avoid using another class as data member , if that's not the case and you have to use it, then use pointer to that another class.
Now, if you are using pointer to the another class , always deep copy , so you have to provide a copy constructor with a deep copy to avoid invalid address assignment .
Or just use smart pointers .