Static objects

Discussion in 'C++' started by SunilC, Sep 25, 2005.

  1. SunilC

    SunilC New Member

    Joined:
    Sep 25, 2005
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    #include<iostream>
    using namespace std;
    
    class A {
    	
    	int a,b;
    	A obj;
    	
    };
    main()
    {
    	cout<< " making of the object \n";
    	A allo;
    	cout << "Object completed develpoped\n";
    	cout << sizeof(A);
    	cout << "now the size of object\n";
    	cout << sizeof(allo);
    }
    
    When I compiled this code it gives the error I . e. incomplete type
    is not allowed.............but when I put static

    Such as
    Code:
    #include<iostream>
    using namespace std;
    
    class A {
    	
    	int a,b;
    	static A obj;
    	
    };
    main()
    {
    	cout<< " making of the object \n";
    	A allo;
    	cout << "Object completed develpoped\n";
    	cout << sizeof(A);
    	cout << "now the size of object\n";
    	cout << sizeof(allo);
    }
    It compiles without error giving the output as 8 in cout <<
    sizeof(A); and the same 8 also in cout << sizeof(allo);

    Can somebody throw some light on the behavior of static object in
    its own class.
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    When its non static you are creating a cycle where the object has an object within itself as a member which is practically impossible to have but when it becomes static its equivalent to global object and so compiler does not give any error.
     
  3. SATYAN JANA

    SATYAN JANA New Member

    Joined:
    Jul 31, 2004
    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Programming
    Location:
    Kolkata
    I'll add one thing that,-
    just declare the class as:-
    class A {
    int a,b;
    A *obj;
    };
    Your problem will be solved. Otherwise, it becomes a recursive definition, which is not allowed. You can surely have a self-referencing pointer.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice