Dear Community,

I know that Java and C# and various OTHER programming languages support a variable type Object, which is basically a variable that can hold ANY kind of variable type, from strings to booleans. I was wondering if this is possible in C++, I REALLY badly need something of that kind, anyone know where I can get something like that?

Recommended Answers

All 18 Replies

If you mean something like the Java 'Object' class which is the superclass for everything, then no, C++ doesn't provide it per se, but you can always implement it by having a common base class which every class inherits and which has the properties of being a superclass to every class in your application.

:D thanks for the suggestion, I was thinking more along the lines of having a class Object. Variables of type Object could be equal to any other value that I define. C++ is great language but sometimes VERY frustrating :D

>I REALLY badly need something of that kind
Perhaps if you describe what you're trying to do, one of us can suggest a solution better suited to C++.

Ok, if you know Java, every class is somehow related to the superclass Object, I know C++ is not that way, but I want to make a CLASS in C++, that can hold a variable of ANY type of data type that I define, so this class, say we name it PObject, a variable of type PObject should be able to hold strings, booleans, floats,doubles,integers,chars, anything I define it to hold. This is simply done in Java or C# by making a variable of type Object, and just setting it equal to any variable type. I hope my explanation jsut clarified my question some more :D:D

>Ok, if you know Java <snip>
I do know Java, but I asked you what you're trying to do, not how you're trying to do it. Most of the time a variant type in C++ is an indicator of poor design, but unless I know the problem you're trying to solve, I can't offer alternatives.

>I hope my explanation jsut clarified my question some more
Not a bit. All you did was restate your original question, which I already understood fully the first time, without adding any new information.

Well, I have no COMPLETE goal for ANYTHING, I just want to make an Object class in C++, just for the sake of it, something that is like the Object data type of C# and Java. It can hold the value of any kind of data type and display them correctly when asked to. That is all I need.

>I just want to make an Object class in C++, just for the sake of it
Okay, then there's nothing stopping you from wrapping all of the built-in types inside a class, with a "one ring to rule them all" Object class at the top. But there's also nothing stopping you from using types outside of that hierarchy without writing your own preprocessor that restricts client code.

>That is all I need.
Why won't I be surprised if you end up trying to write Java-esque code in C++? :icon_rolleyes:

Ok no offense Narue, but that is not helping me at all, taking quotes from my reply and adding an opinion or sometimes fact to them doesnt help me at all, I know there is nothing stopping me from doing things like you said, here is the problem, I DONT KNOW HOW!. That is why I came here to ask, I knew that from the beginning. I would honestly APPRECAITE if you could SHOW me how to do that, I am not asking for the entire code , I am just asking for an example, like this:

public class Object
{
    char* ch;
    double d;
    int i;
    float f;

    public Object()
    {

     }
}

What you are looking for is template. I think this is what you are trying to
accomplish.

template<typename Type>
class Object{
protected:
  Type var;
public:
 Object(){}
 Object(const Type& initValue) : var(initValue){ }
virtual string toString()const ; //leaves the derived to implement this
}

Then you can do something like this :

class Int : public Object<int>{
public:
 Int() : Object<int>(0) {}
 //convert to string
 string toString()const{
  stringstream strm;
  strm << var;
  return strm.str();
 }
};
class Float: public Object<float>{
public:
 Float() : Object<float>(){}
 string toString()const{
 stringstream strm;
  strm << var;
  return strm.str();
 }
}

Of course I don't see why you would need this for your situation
because I don't know your situation. But I assume this can be
helpful it you put important information for each data-type.

commented: Very Helpful +1

Ahh thank you firstPerson, that does help me a lot, and I very much appreciate the code that you invluded, the typename Type part I dont understand though, can I change Type to be anyhting I want or what? :D:D please do clarify

In java all you have to do to create a template class is this :

class List<T>{...}

In C++ its not that simple. The syntax for a template class is this :

template<typename Type>
class List{...}

The above code tells the compiler that the class List is a template
class. It's body will only be instantiated when you create a List object.
The "typename Type" tells the compiler that "Type" can be anything,
int, float, double, or string. Think of it as a generic data type.
For example you know how you declare a int variable like so :

int var ; //declare var as int

Think of Type, as anything. It can be int, float or whatever, depending
on how List is instantiated. So this code :

Type var; //declare var as Type

says that var is a variable
of type Type. Again Type can be int or float or something else.

Oh ok, ya that is perfect, I have one problem though, I make the Object class and a Flaot class with the examples you gave me, and in the .cpp file that tests this class, using the code:

#include <iostream>
#include "IFloat.h"

using namespace std;

void main()
{
	IFloat obj;
	obj.Store(2.3);
	cout << obj.toString();
	getchar();
}

The output is EXTREMELY weird and it is like 3 lines with the same characters in the same places in each line, how do I fix this?

>I DONT KNOW HOW!
You don't know how to write a simple class? Not much of a Java programmer, are you? Here's the Beginner's C++ 101 code for what you're asking for (a C++ version of Java's object model):

#include <iostream>
#include <sstream>
#include <string>

class Object {
public:
  virtual bool equals ( Object *obj ) const = 0;
  virtual std::string toString() const = 0;
};

class Integer: public Object {
public:
  Integer ( int value )
    : _value ( value )
  {}

  virtual bool equals ( Object *obj ) const
  {
    return _value == ((Integer*)obj)->_value;
  }

  virtual std::string toString() const
  {
    std::ostringstream out;

    out<< _value;

    return out.str();
  }
private:
  int _value;
};

int main()
{
  Object *foo = new Integer ( 12345 );
  Integer *bar = new Integer ( 0 );

  std::cout<< foo->toString() <<'\n';
  std::cout<< bar->toString() <<'\n';
}

It's called polymorphism, you might have heard of it. Repeat as necessary until you get bored, and add whatever other features for each type you're interested in. You can get as big and complex as you want. But since you apparently don't know anything about anything, that kind of limits what's possible. :icon_rolleyes:

Or, if you want an actual variant type rather than a custom object model, I'd suggest searching google for the umpteen attempts in C++ by everyone and his brother. You should have done that before bothering us, but that's too much to hope for. But be warned: they're usually useless and quite often overly complicated.

>> in C++ by everyone and his brother

On the contrary, its, "by everyone and his mother" :)

Thanks first Person, and wow Narue, honestly don't know why you hate people so much, I understand you signature now, just because people are not as understandable as you MIGHT be, doesn't mean you make fun of them. Honestly man, I dont know what bit you in the butt but obviously your to high and almighty to answer questions for people that need help. I dont know if you will take htis into heart, but I hope you remember when you were programming early on, you were not born the capability to program anything. We all learn things step by step, and just because your higher up on the way doesnt make anyone less better than you. Your probably to arrogant/ignorant to understand what I said, but since my moral ethics take the better of me, I am obliged to thank you for your code, even though it alongside ignorant comments. So thank you for your "help". Just a wild guess that, I am thinking your will into your 40s/50s, but thats just a guess.

>obviously your to high and almighty to answer questions for people that need help
I answered your question. Then you shot back with "I'm too clueless to understand anything, gimme code!".

>I hope you remember when you were programming early on,
>you were not born the capability to program anything

I remember quite clearly. I also remember that I didn't have anyone to lean on for help. I had to figure everything out by myself, so I'm especially unsympathetic toward newbies these days who have the vast resources that would have given newbies a spontaneous orgasm when I was learning, yet still can't survive without hand holding.

>Just a wild guess that, I am thinking your will into your 40s/50s, but thats just a guess.
Early thirties. Though I'm not sure how that's relevant.

commented: I remember those days too. Some bloody newbs don't know they're born! +2

For you info, look back at my post, I didn't ask for COMPLETE code, I just asked for an example, and I am sorry the world was too undeveloped or you didn't know or couldn't afford the internet back when you were learning, but people SHARE resources and develop a COMMUNITY, why the hell are you even here if you hate helping NEWBIES , and I also am not a NEWBIE, I actually took a college course on C++ and Java, but yet again obviously your too egotistic to help other people. I still don't know why you are even registered on a FORUM(a roman word referring to a place where people congregate and share ideas and trade good AND KNOWLEDGE) when you are reluctant to do that.

>but yet again obviously your too egotistic to help other people
It seems you've failed to notice my post count and overwhelmingly positive approval ratings. Perhaps the problem is with you rather than me. :icon_rolleyes:

>I also am not a NEWBIE
I beg to differ, though I'm sure you'll disagree because you appear to see "newbie" as some sort of insult. It's not. N00b yes, but not newbie.

>I actually took a college course on C++ and Java
If that's the extent of your experience then you're absolutely a newbie. A college course is just enough to show intelligent people how little they know, and hopefully encourage a lifetime of learning. It's important to evaluate yourself objectively and recognize your limits.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.