0
#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.

3
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by VatooVatoo
0

>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();
}
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.