how can a regular class have a singleton subclass in c++ - c++

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.

Related

C++ How to access an object of another class?

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.

What is the object-oriented idea I'm trying to get at with my scenario?

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

c++ Factory. Child constructor not accessible from parent

I'm making a socket factory. I want every external application to use the interface of the Socket class that is the parent of a few classes (ServerSocketTCP, ClientSocketTCP, ServerSocketUDP and so on) because eventually socket will be use to read and write independently of the type, simplifying the use of them. So sockets will be only constructed by a socket static member (The factory). That why children constructors are protected in order to avoid users to create them.
Here is where I got the error:
class A{
protected:
A();
public:
static A* createClass(int _type){
switch(_type){
case 0:
return new B();
case 1:
return new C();
default:
return nullptr;
}
}
}
class B: public A{
protected:
B();
}
class C: public A{
protected:
C();
}
Then the compiler says that the constructors of B and C are not accessible from A. Is there any way to do what I want? I thought that it was possible to access children protected member but now I see that not because the access inheritance...
There are problems with your code. Except for missing ; after the class definition you are also implementing the factory in a wrong way.
In general you have a Producer that produces products. The products all share a base class that normal users should not be able to instantiate (e.g. pure virtual or protected ctor). According to what the client chooses, the Producer creates an instance of the product and delivers it back. So if your product ctors are private you need to declare the producer as a friend in order to be able to access the respective ctors.
Now the producer delivers some pointer to a base product which can be downcasted to the type you need. So an compiling example (picked yours and modified it accordingly) would read like this:
class Producer;
class BaseProduct {
protected:
BaseProduct() {}
};
class Product_B : public BaseProduct {
friend class Producer;
private:
Product_B();
};
class Product_C : public BaseProduct {
friend class Producer;
private:
Product_C();
};
class Producer{
private:
Producer();
public:
static BaseProduct* createProduct_Class(int _type){
switch(_type){
case 0:
return new Product_B;
case 1:
return new Product_C;
default:
return nullptr;
}
}
};
Please be aware that using the factory pattern wrongly can result quickly in anti-patterns.
EDIT: Plus you should not forget to extend your producer class to manage deletion etc. There are many books and websites that handle all kinds of patterns. One good book is "Object-oriented Software Engineering from Bernd Brügge", but of course there are a lot more of them.
In the code you've given, the factory method can't even see the B and C class definitions, so it can't possibly use them, no matter whether a parent can access a child's protected members or not (it can't, as noted by Marco A.).
You need to move the implementation of the factory method to a cpp file where it can see all of the class defintions. Then you'll get errors about the constructors being protected, and you can deal with those appropriately (presumably by making friends).
Yes, th compiler is complaining because B and C constructors and `protected, and no friendship exists. So A cannot call those constructors.
The correct design is to separate the Factory type from the class hierarchy, not to put it in the base class.

correct Inheritance/class structure

i want to write a library for linear program solving. Thereby several solvers such as cplex or gurobi are used. What i already have is an interface for each of them (all containing the same functions wrapping them to solver specific code).
Now I want to have a class 'LinearProgram' which can be instantiated e.g. by LinearProgram("cplex") which then invokes the cplex solver.
My first idea was to use a super class 'solver' which is a base class of all solver interfaces containing the respective functions as virtual declarations. But then I get an abstract class which can not be instantiated.
So in LinearProgram i wanted to have a variable Solver which is instantiated depending on the string given in the constructor.
I'm sure a proper solution is quite obvious, but all I can think about in the moment is not satisfying.
Thanks for your help.
This illustrates what you describe:
class Solver {
...abstract base
};
class SolverFactory {
public:
Solver* NewSolverWithName(const std::string& pSolverName);
};
class LinearProgram {
public:
LinearProgram(const std::string& pSolverName) :
d_solver(SolverFactory::NewSolverWithName(pSolverName)) {
}
private:
some_auto_pointer<Solver> d_solver;
};
class cplex_Solver : public Solver {
...
static std::string Name();
};
Solver* SolverFactory::NewSolverWithName(const std::string& pSolverName) {
if (pSolverName == cplex_Solver::Name()) {
return new cplex_Solver();
}
...
}
This is a job for two different design patterns combined.
The first is the Envelope Letter pattern, and the second is the Strategy Pattern.
Keep on with the base class that you currently have and make a derived class that simply forwards the call to an embedded pointer to the base class. The derived class is now something you can freely pass around by value.
The base class could also contain a static member function that returns a pointer to the base class. This static member function would allow you to instantiate a derived class by using a string name to look it up. That provides a convenient way to select an algorithm at runtime.
But people who knew which derived class (which strategy) they wanted could just create one with 'new' and stuff it inside an instance of the envelope class.
You can optionally do away with the envelope class if you decide to just use a shared_ptr to the base class instead.

Can you have protected nested classes in C++?

I have a class that only really ever needed by classes in a certain class hierarchy. I wanted to know if it is possible to nest the class in the highest class's protected section and have all the other classes automatically inherit it?
"Inherit" is the wrong word to use since it has a very specific definition in C++ which you don't mean, but yes you can do that. This is legal:
class A {
protected:
class Nested { };
};
class B : public A {
private:
Nested n;
};
And code that is not in A or something that derives from A cannot access or instantiate A::Nested.