Create Object??

Posted on 2003-02-20
Medium Priority
Last Modified: 2010-04-01
I have already put this question and some of the friends tried to answer it.How to create an object in c++ without instantiating the class??

someone told to do like this.

class Test
data membares;

but this again creates object..
I am trying to say what i understood....
As its known every object has pointer to its own address i.e this pointer.
So have a static method in the class and return the address of the this pointer from that static function.
And call that static method by the calss name.Store the returned address in some variable and use that variable as object.I am making any sense??
Question by:eureka2k
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +4

Expert Comment

ID: 7988874

Accepted Solution

sjyi earned 80 total points
ID: 7988904
An object by definition is an instance of a class.

You can define a class which has nothing but static members.  The data members are "class" members, not object members.  The member functions are static, meaning no "this" pointer when invoking the member functions.  You can use this "class" object.

When you do this (provided there are no inheritance), you have essentially created a static (file scope) C structure, but using the class name to reference it.  You can access the class data members using full scope, e.g. &class:datamember.

Expert Comment

ID: 7992507
It is not possible in any sense in c++ because it is an Object Oriented language. With static member function, you can   call the function through class reference But It doesnot mean that this pointer is of an Object of this class. Object can only be created through instanciating a class.
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 12

Expert Comment

ID: 7993618
What you ask is impossible, you want to create an object without instantiating the class.

Hint: "Instantiating the class" means to create an object and creating an object means to "instantiate the class". The two are two different ways to say exactly the same thing.

In a way you ask to create a painting without ever doing the action of painting. Of course you can create a copy of a painting by a xerox machine or something but that ain't a painting. A painting by its very definition is made by someone doing the job of painting it.

Another hint: static functions has no this pointer.
You can't take the this pointer from a static function, it doesn't have a this pointer to return.

What you ask for doesn't make sense.

Why on earth would you want to do something that doesn't make sense? Go and draw me a square circle and I can give you an object that wasn't instantiated.


Expert Comment

ID: 7993746
Static function member doesn`t have 'this' pointer and can use only other static members of this class and can`t return 'this' pointer. But you can call non-static member function of class without instancing:

class Test {
data membares;

Test &x = *(Test *)NULL; <-- NO INSTANCING



If function() - is static member - it will be OK anyway, and if function() is non-static member but doesn`n use any non-static members variables of this class (but can use non-static members functions with same conditions or any static functions) - it will be OK too. All other cases - you will have Access violations about address 0x00000000 (NULL + offset of member variable) (Windows has small guard page from address 0x00000000 for using NULL pointers - using this page will be subject for exception always) Certainly, if function is non-static 'this' pointer will be NULL - you initialise it yourself :)

Expert Comment

ID: 7995792
i think the question asker is looking for a singleton

in the below example, you can only have a single copy of the singleton during the entire duration of the program.  here the object is of course being initiated but it is done so only by the class itself.  you can access the auto-initiated object using the static method obj().  other than this, all methods of singleton are normal methods and you can do whatever you want in them, including using "this"

for example, to call the test() method, use,


--- cut from here ---
class singleton {

  obj() {
    static singleton object;
    return object;
  }; // obj

  test() {
    std::cout << "test" << std::endl;
  }; // test
  singleton() { };
  singleton(const singleton&) { };
  singleton& operator=(const singleton&) { return *this; };
  ~singleton() { };

}; // singleton
--- cut from here ---

Expert Comment

ID: 8024841
Static function can not return this pointer.
LVL 12

Expert Comment

ID: 8025156

Joker's "solution" isn't a solution.

It require you to make a null pointer cast into a pointer of the specified type and then call a function through that null poointer. That is not valid portable code.

p -> func()

if p is a type that can legally call func() then if p is a null pointer value then the effect of such a statement is undefined.

Check up the meaning of "undefined" in language standards.

Null reference is even worse than a null pointer.

In short Joker's solution is a joke.

And yes, static functions do not have this pointer.

The point is that the original question asks for something that is impossible and doesn't make sense. Which is what we have tried to say here many times.

Now, eureka2k, accept an answer and close this silly question and move on to more fruitful things in life. Things that make sense and so on.


Expert Comment

ID: 8026269
> "The point is that the original question asks for something that is impossible and doesn't make sense. Which is what we have tried to say here many times."

salte, yes, it is impossible to use a class without creating an object but from his/her question, it seems a singleton might be what s/he is looking for, as that would give the *illusion* of using the class without explicitly creating an instance

for example, in the example i gave above, you never ever create a singleton object ( in fact, as you probably noticed, you can't ) but you can access a copy of it via the static obj() method, which creates the instance behind the scenes.  if the user of the singleton class had the header file only, s/he would have no idea that an object was being actually created in the background.  well, any reasonable c++ person would know that but a newbie might easily be fooled with such a trick
LVL 12

Expert Comment

ID: 8026579
well, strictly speaking you do create the object.

class foo {
   static foo bar;
   ...other members...

   static foo & baz();

   ...other functions...

If you have a header file like this then you also typically have a cpp file like the following:

#include <foo.h>

foo foo::bar(....); // global object constructed.


So the object is still constructed. It's even constructed before main() is called which is probably why you get the feel that it isn't ever constructed.

It is possible he wants a singleton object, however, the above manner is also useful for non-singleton objects, you could have a static function which acted almost as a constructor and constructed the object on the fly from heap for example without having the actual constructor accessible from outside. This is typically used for cases where you create a class with a data layout that depend on data following the actual class for example:

class string_t {
   size_t len_;
   size_t sz_;
   int refs_;

   void * operator new(size_t sz, size_t ssz)
   { return malloc(sz + ssz); }

   void * operator new(size_t /* sz */, void * p)
   { return p; }

   string_t(size_t len, size_t sz) : len_(len), sz_(sz), refs_(1) {}

   char * str_() const
   { return reinterpret_cast<char *>(this + 1); }


   static string_t * mk_string(const char * str);
   const char * str() const { return str_(); }

   ....other stuff....

string_t * string_t::mk_string(const char * str)
   size_t len = strlen(str);
   size_t sz = len >= 100 ? len + 1 : 128;

   string_t * s = new(sz) string_t(len,sz);
   strcpy(s -> str_(), str);
   return s;

Here the string data is placed immediately after the class and this is enabled by hiding the constructor so the user cannot access it and he can only create objects of the class using the static member function mk_string() which ensures that the data is allocated in that exact manner.

I agree that you should rather use std::string than such a class but that is beside the point here. The point is that by making the constructor or the object available through a static function you can hide the actual construction. The object is still constructed at one time or another (either in that static function or the function accesses an object previously constructed).

His original request still makes no sense. It is possible he meant a singleton class (class with only one instance) but it is also possible he was just trying to be "smart" but it turned out it wasn't so smart after all.

LVL 12

Expert Comment

ID: 8026591
I notice that after eureka2k had his original posting here, he hasn't even once commented on the replies he got, which also makes me believe he didn't really have a problem or issue that needed to be solved and that he just made a weak attempt at being "smart".


Expert Comment

ID: 8026621
> "His original request still makes no sense. It is possible he meant a singleton class (class with only one instance) but it is also possible he was just trying to be "smart" but it turned out it wasn't so smart after all."

granted; that might be the case, too and as he didn't give any feedback, i guess we'll never know...  oh well, more than enough discussion for 20 points ;-)

Expert Comment

ID: 8868889
This question has been abandoned. I will make a recommendation to the moderators on its resolution in a week or two. I appreciate any comments that would help me to make a recommendation.

In the absence of responses, I may recommend DELETE unless it is clear to me that it has value as a PAQ. Silence = you don't care.


EE Cleanup Volunteer

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question