Thread: Interesting run-time error in a simple class definition

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    61

    Interesting run-time error in a simple class definition

    Hi
    Please look at this code:

    Code:
    #include
    using namespace std;
    
    class MyClass
    {
    private:
    int d;
    public:
    int x;
    };
    int main()
    {
    MyClass a;
    cout << a.x; //gives runtime error: The variable 'a' is being used without being defined.
    }
    I only added one function

    Code:
    #include
    using namespace std;
    
    class MyClass
    {
    private:
    int d;
    public:
    int x;
    void print(){ cout << d;};
    };
    int main()
    {
    MyClass a;
    a.print();
    cout << a.x; //Now it works
    }
    But if i write a.print(); after cout << a.x; it gives me run-time error again.

    So why is this so?
    It says: "a' is being used without being defined." But when i call function it doesnt give error. So is calling function means defining a class?

    I do not understand why it gives error first and third but doesnt give error second one.

    Can you please help me.
    Thanks.

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Indenting wouldn't kill you...

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    But both x and d are uninitialized! There is nothing in that code that would assign them a know value. So, can't you see the problem with it?

    I would have thought this would give a compile-time warning, but may-be it causes a run-time error in debug settings...
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. class definition error
    By rahulsk1947 in forum C++ Programming
    Replies: 4
    Last Post: 05-16-2009, 11:26 AM
  2. Sending an email in C program
    By Moony in forum C Programming
    Replies: 28
    Last Post: 10-19-2006, 10:42 AM
  3. Simple thread object model (my first post)
    By Codeplug in forum Windows Programming
    Replies: 4
    Last Post: 12-12-2004, 11:34 PM
  4. Difficulty superclassing EDIT window class
    By cDir in forum Windows Programming
    Replies: 7
    Last Post: 02-21-2002, 05:06 PM
  5. time class
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 12-11-2001, 10:12 PM