Tuesday, October 23, 2012

Question 14: Predict the output.
    class
    {
    public:
        void display()
        {
            std::cout<<"Display function without any class name";
        }
    }classWithoutAnyName;

    int main()
    {
        classWithoutAnyName.display();
    }



    Options:
    (a) Display function without any class name.
    (b) Runtime Error
    (c) Compile Time error: Class doesn’t have any name.
    (d) None of the above.


    Answer: a

3 comments:

  1. We can have a class without a name in C++ .

    Object Creation :
    Objects of such a class can be created along with the class definition as shown above .

    Passing Arguments to Function :
    Cant be done . Although we can always pass a void* . But the class won't know how to handle it .

    Constructors and Destructors :
    Such a class cant have any .

    ReplyDelete
    Replies
    1. Quoting "Passing Arguments to Function :
      Cant be done . Although we can always pass a void* . But the class won't know how to handle it"

      Can you please explain? If you are allowed to pass a void*, then you can definitely know how to handle it... isn't it?

      Delete
    2. Hi Kaush.rasto,

      It is allowed to pass an argument to a function, as object is created so this pointer exists for the object created.
      For example:
      Following code is valid too.....
      class
      {
      public:
      void setValue(int value)
      {
      m_data = value;
      }
      void display()
      {
      std::cout<<"Display function without any class name"<<"\n Value is : "<<m_data;
      }
      private:
      int m_data;
      }classWithoutAnyName;

      int main()
      {
      classWithoutAnyName.setValue(20);
      classWithoutAnyName.display();
      }

      Delete