C++ :: How To Create A Singleton Class

Oct 6, 2013

I've tried to program a Singleton class. But the problem is that I don't know how to access the g_pInstance() function. Because this is not working because the constructor and deconstructor is private:

Singleton::g_pInstance()
Code: #include <iostream>
using namespace std;
class Singleton
{

[Code]....

I'm not sure of how to access any object, function, variables in the class when you are using a Singleton. How do you access that?

I'm just asking because I want to know how to do that if I have to use a Singleton sometime when I'm programming.

View 5 Replies


ADVERTISEMENT

C++ :: Singleton Class For User Settings?

Oct 11, 2014

My current idea of how to work with user settings goes like this:

1. Create a class to hold all of the user settings.
2. Use that class to load/save/hold settings in memory.
3. Create an instance of that class once in the entry point of the program (int Main or whatever).
4. Pass, by reference this same class instance around to all of the other classes that need the user settings.
5. Once all other objects deleted, save and then delete the User Settings class.

I created a psuedo-code example below of this. My question is if this is the best way or should I be doing something else. In particular, I am wondering if somehow I can avoid passing the settings class by reference all of the time. Would this be a good case scenario for a "Singleton" type class?

#include <string>
class UserSettings {
private:
std::string SettingOne;
int SettingTwo;
bool SettingThree:

[Code] ....

View 9 Replies View Related

C/C++ :: Declaring Map Global Or Wrap In Singleton Class

Jul 13, 2014

#include <map>
#include <iostream>
#include <stdexcept>

[Code]....

SuperSmartPointer<int> ptr4((int*)ch); this line gives error error as double deletion will occur.

Solution :
1) make the reference map global variable.
2) wrap the map in a non-template singleton class.

View 1 Replies View Related

C++ :: Singleton Base Class - How To Implement GetInstance Function

Aug 20, 2014

I'm playing with the idea of a singleton base class, but I'm having an issue with how to implement the GetInstance() function in the base class. Since I'm trying to make this ridiculously simple for the child, I'd like to handle that in the base.

class Singleton {
private:
static Singleton* instance;
Singleton() { Construct(); } // Private to avoid other instances

[Code] .....

It would be easy to use like so:

class Hello : public Singleton {
private:
std::string hello;
void Construct() { hello = "hello"; }
public:
std::string GetHello() const { return hello; }
};

Then the instance would be handled like so:
std::cout << Hello::GetInstance()->GetHello();

View 12 Replies View Related

C++ :: Singleton Class - Auto Seems To Return Wrong Type

Jul 18, 2013

I am trying out a technique for a singleton class:

// access controlled singleton, accessed through function "instance()"
// singleton is constructed in this function
// so that constructor and destructor will be used
class single {
// private constructor/destructor

[Code] .....

Playing around with the code in main(), I am having trouble with auto:

single& s = single::instance(); // works fine
auto a = single::instance(); // error ~single() is private

When I make the destructor public, the output of the program is:

ctor
dtor
dtor

So I fixed this by typing auto&. I'm still confused though, why wouldn't auto know I am returning a reference?

View 2 Replies View Related

C++ :: How To Create A Class Object Inside Another Class

Feb 20, 2015

My thought is that I would need to establish a variable for the class in the header and call the class within the .cpp file

//class A.h
B b;

Then in class A, to create the object and use a method from the object I would -

//class A.cpp
A::A(){
b();
}
int someAmethod(){
b.bmethod();
}

View 6 Replies View Related

C++ :: Getting Singleton Instance

Oct 25, 2014

Code:

class BoundingBoxTest : public DemoApplication {
public:
#ifdef DYNAMIC_CHARACTER_CONTROLLER
btCharacterControllerInterface* m_character;

[Code] ....

I am creating the object by calling : BoundingBoxTest::Create();

Do I make a getter to retrieve the demo object or do I build on the Create() method... So that it will return the instance if it is not null. and creates one if there is none?

View 3 Replies View Related

C++ :: Constructors In A Singleton

Apr 6, 2013

I need to implement a singleton, so I've been reading about it online and I'm still not quite sure about all the types of constructors I need to declare:

Code:
class my_singleton {
private:
my_singleton();
my_singleton(my_singleton & X);
my_singleton(const my_singleton & X);

[Code] ....

Is this OK?

View 8 Replies View Related

C/C++ :: Creating A Singleton Pointer?

Jun 26, 2014

I have a class in my application that only needs to be created once, but the object needs to be available to all other classes in my application if necessary. Since declaring everything static can be restrictive (as I understand), I created a class like this:

class Foo {
// Data members
// Constructor/Destructor
// Functions
};
extern Foo* myFoo = new Foo();

And then the global variable gets deleted at the very end of the main method when everything is done:

#include "Foo.cpp" // (yes, I know this is normally bad, this is how I'm required to code)
int main() {
// do stuff
delete myFoo;
return 0;
}

These won't link, though, because I get undefined reference linking errors to myFoo wherever I use it. I'm pretty sure this means I'm creating a singleton wrong, but I'm not sure what I'm doing wrong -- there's no const conflicts and the pointer is properly initialized (to my understanding). If there's a better way to do this than extern, I'm completely open to it, as long as it's understandable and works.

View 9 Replies View Related

Visual C++ :: How To Use Watch When Using Singleton

Aug 24, 2014

I have code like this:

Code:
if (S::I().File.isDirectory(arg, S::I().Stat.workingPath)) {
// find out if there is -r option after 1st argument to join files
src_temp.join = true;
S::I().Stat.getRegEx = true;
}

The S is singleton class and I() returns instance of Singleton; there is a Stat object too. When I debug (line by line) I would like to see what values are in the Stat object. Is it possible to do it using Watch panel in Visual Studio 2010?

View 7 Replies View Related

C++ :: Singleton Destruction Order

May 28, 2012

I've been upkeeping a mess of a code recently, that uses "pseudo" singletons. Basically, the current code has "Initialize_All" static functions that initializes all the singletons in a given order. At the end of the program, we call "Destroy_All", and destroy everything in the reverse order.

The code is actually heavilly dll'ed, and Initilize_All and Destory_All are referenced counted. We ask that any client who uses our code call Initialize_All first and then Destroy_All when they are finished. The first Initilize_All will initialize everything, and the last Destory_All will delete everything.

This is showing its limits.

I'd like to move us to a fully singleton design. The singleton pattern means we don't have to use an Initilize_All, and each singleton can manage construction dependencies by itself (we are mono-threaded).

Each singleton is "clean", so it is cleans itself up at dll destruction.

The big question is this one:

If there is a singleton dependency during destruction, eg: ~A requires an instance of singleton B (which is in another DLL), are we guaranteed proper behavior?

Or, is there an "Static de-initialization order fiasco"?

If yes, are there any design that can combat this fiasco, short of having each singleton register itself in a manager, that will destroy them in reverse order?

View 6 Replies View Related

C++ :: Out Of Bounds Access (Array / Singleton)

Feb 3, 2014

#include <iostream>
int main() {
int bit = 1;
int init = 0xf ^ (1 << bit);
char* c = new char(2);
sprintf(c, "%x", init);
std::string initVal = std::string("4'h") + c;
std::cout << initVal << std::endl;
}

Above code is compiling as I expect it to be.

Problem is when I run it, it prompts me the following message:

Out-of-bounds access (ARRAY_VS_SINGLETON). Passing "c" to function "operator +(HSTString const &, char const *)" which uses it as an array. This might corrupt or misinterpret adjacent memory locations.

View 2 Replies View Related

C++ :: Singleton Pattern - Delete Pointer Twice

Feb 22, 2012

environment : qt creator 4.7

code:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class singleTon {

[Code] ....

this is a singleton pattern first,it doesn't matter, why I could delete this pointer twice?because the gcc compiler?That mean in the surface, "delete pInstance1;" this movement just mark the memory pInstance1 has been deleted but not real?does any one encounter this phenomenon?

View 7 Replies View Related

C++ :: Singleton Design Pattern - Not All Control Paths Return A Value

Jan 17, 2013

I have the following code where I use the singleton design pattern, but I get the warning:

warning C4715: 'CM::Instance' : not all control paths return a value

Code:
CM& CM::Instance() {
DWORD dwWaitResult = WaitForSingleObject(mutex, INFINITE);
switch(dwWaitResult) {
case WAIT_OBJECT_0:

[Code] ....

How can I fix this warning?

View 4 Replies View Related

C++ :: How To Create A Container Class

Feb 9, 2013

I know that it's a class that contains data from another class I just do not know how to make them both work together.

View 1 Replies View Related

C++ :: Singleton Design Pattern - Why Copy Constructor Not Made As Private

Jul 9, 2014

I was going through Singleton design pattern and get to know that objects can be created only by static function of that class and constructors are make private.

My question is, why assignment operators are not made private through which we can create a copy of already existing object.

I tried below code and assignment works, so I have new object sc3. I know that its referring to memory of sc1 but finally I was able to create object without using static function.

Also, why copy constructor not made as private.

Below is code:

#include <iostream>
using namespace std;
class Singleton {
private:
static bool instanceFlag;

[Code] .....

View 3 Replies View Related

C++ :: How To Use A String To Create Class Object

Dec 24, 2014

I wanted to create a new class object and I want to name it from a string. Something like this:

string name = "Mike";
Customers name;
//to create a new object in customer class using the name string

Is there any way to do this?

View 11 Replies View Related

C++ :: Create A C Wrapper Around A Interface Class?

Mar 14, 2013

I need to create a C Wrapper around a C++_Class and in between needs to be an Interface-Class. The Interface-Class is needed, cause there are more C++_Classes which are kinda equal.

Hierarchicaly it would somehow look like this:

=> XY-Process which is calling the CWrapper
==> CMeasureWrapper.c// <-- CWrapper
===> CMeasureWrapper.h// <-- CWrapper Header
====> IMeasurement.h// <-- Interface-Class
=====> CMeasure.cpp// <-- C++_Class
======> CMeasure.h// <-- C++_Class-Header

My Output after compiling.(files will follow)

// CMeasureWrapper.c | CWrapper
#include "CMeasureWrapper.h"
uint32_t gu32_objectHandle;
uint32_t gu32_measureType;
int32_t addNewMeasureObject(uint32_t u32_measureObjType)
{
int32_t t_status = 0;

[Code]...

It's the first time i'll try to build an CWrapper or even a wrapper. So maybe the Project-Properties need to fit as well.

The project itself is called "Platform" with following settings in:

C/C++ -> Advanced -> Compile As -> "Compile as C++ Code (/TP)"

This property on the CMeasureWrapper.c is switched to:

C/C++ -> Advanced -> Compile As -> "Compile as C Code (/TC)" but only on this file!

I'm not sure if it's necessary, the file is of .c type, so I wasn't sure.

what I am doin wrong? Not just depending on the error output, I mean on the whole project. Is there anything else which will not work with such a combination of CWrapper, Interface and C++_Classes? If there are any questions, just throw them at me

View 2 Replies View Related

C++ :: Cannot Create Struct That Contains Instance Of A Class

Sep 4, 2013

I'm trying to learn as much C++ as I can. I was writing a program that mixes linked lists and classes. There is the class "Obj" which only holds an integer called 'data' and the classic "struct node" structure for linked list, but this time the "node" structure will hold an instance of "Obj" Class and the next* pointer.

#include <iostream>
using namespace std;
class Obj {
private:
int data;
public:

[code]....

View 2 Replies View Related

C++ :: Create A Thread To A Class Function

Jan 25, 2014

I'm trying to create a thread to a class function, but it doesnt work for me...

The function : void Server::RecMsg(SOCKET &socket)

the call : std::thread GetMessages(&Server::RecMsg, ClientSocket);

I get the error : "Error1error C2064: term does not evaluate to a function taking 1 arguments"

View 1 Replies View Related

C++ :: Create Objects From Abstract Class

Oct 13, 2013

I am working on a project that requires me to create objects from a abstract class that has 2 child classes (that need to be derived). Any examples on how to do this? I looked online and the examples were pretty vague. the main error that I am getting is when I make a temp object with & in front of it (such as Employee &genericEmp) it throws a must be initialized error.

View 6 Replies View Related

C++ :: Dynamically Create Class Objects?

Nov 3, 2013

regarding dynamic vector.

Shape2DLink.cpp
void Shape2DLink::InputSensor()
{
string shape,type;

[Code]....

So i'm actually using polyphormism for calculating the area of the cross and other shapes. so how do I actually make use of dynamically create an object this way?

do I create them in my Shape2DLink or in my individual child classes?

View 9 Replies View Related

C/C++ :: Allow User To Create A New Class Instance?

Dec 4, 2014

I am creating a program that allows a user to create multiple 'sequences' and multiple 'filters' and then apply a filter to a sequence.

Each sequence and filter is an array of values.

How do I go about allowing the user to create a 'new' sequence and then store the location so I can access it again later? Once they have created a new sequence they can go on to create another sequence and ten maybe a filter and then another sequence etc etc .. and then they can select sequence 1 and edit the values if they so wish.

They would be asked how many sample values for the sequence, and then I would create a sequence with that many values and an id (1,2,3,4...). They could then enter this id to view/edit the sequence.

The entering/editing values part I am fine with. I just don't know how to allow them to create multiple new instances of a class without using an array so something like..

sequenceClassName somearray[10];
int i;
*create a new array*
somearray[i].create_class(how_many_samples)
i++ //so next sequence they create is 2,3,4.. etc

- this then calls the member function that creates an array using 'sample_values = new float[how_many_samples]' and the user can input their data and edit it whenever by entering the id which will correspond to the somearray[i].

However that approach only allows them to enter a maximum of 11 sequences. It all depends on how big I make that initial array and it just seems like the wrong way to do it.

( how to interact with them, just how to create multiple classes and recall them later to access the data!)

View 2 Replies View Related

C++ :: How To Create Template Method In A Class

Jul 8, 2014

Code:

class A {
public:
template<class T>
ObjectsBase* createObject(T* objType, Ogre::String name, Ogre::Vector3 position);
};
template<class T>
ObjectBase* A::createObject(T* objType, Ogre::String name, Ogre::Vector3 position);

My goal is to create any ObjectBase* derived object and return it to class A....

View 6 Replies View Related

C++ :: Create A Class Representing Project Activities

Mar 24, 2013

Create a class representing project activities. In this class include all the required data members and member functions. Each activity should have a record of activity duration, calculated early start, early finish, late start, late finish, free float, and total float. Each activity may or may not maintain a list of its successors and predecessors. Provide your design in UML and implement it in C++ using an interface head file and an implementation source file. I do not understand classes or UML designs.

View 2 Replies View Related

C++ :: Create 5 Instance Object Of Class Test?

Apr 27, 2014

I am new to C++. I am trying to create 5 instance object of class Test. I wonder if these two codes are the same.

Test testArray[5];
//which one is the correct way or what is the correct way?
for(i=0;i<5;i++)
{
Test testArray;
}

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved