#include<iostream.h>
#include<conio.h>
typedef class
{
     int i;
     float b;
     public:
     obj()
     {
	cout<<"\n Is this constructor \n";

     }
     void show()
     {
	cout<<"fkjhfg";
     }
}obj;

void main()
{
     clrscr();
     obj o;
     o.show();
     getch();
}

In this code ,of Anonymous class object is calling the show function ,but its constructor is not called. Can some body Explain me this behaviour of the anonymous class.

>but its constructor is not called
The constructor is called, you just didn't define it. This:

obj()
{
  cout<<"\n Is this constructor \n";
}

is not a constructor. It's an ill-formed member function that happens to have the same name as your typedef. If your compiler doesn't warn about this (as well as void main and pre-standard headers), you need a newer compiler.

The problem is that you're confused about the difference between a class name and a typedef tag. A typedef tag does not act in place of a class name, but since C++ doesn't require an explicit class keyword when instantiating objects, I can't imagine why you'd even want to do this. The following code is much much better:

#include <iostream>

class obj {
public:
  obj()
  {
    std::cout<<"This is a constructor\n";
  }

  void show()
  {
    std::cout<<"fkjhfg\n";
  }
};

int main()
{
  obj o;
  o.show();
  std::cin.get();
}

In C++ a struct or class needs to have a name to have a user defined constructor. The compiler will also generate the usual compiler generated constructors, but you can't get at them normally.

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.