Search code examples
c++xcodeoop

Calling object without creating it, in CPP Oops


In the code below unfortunately I didn't create/name any object and when compiling I didn't get any error and also was able to access member function. How I need to this behaviour is this something temporary object created in stack if so if i want to access somewhere later in the code can I access same.

#include <iostream>
#include <string>

class Person {
public:
    std::string name;
    int age;

    Person(std::string n, int a) : name(n), age(a) {}
    void getInfo() {
        std::cout << "Name : " << name << std::endl;
        std::cout << "Age : " << age << std::endl;
    }
};

class Student : public Person {
public:
    int rollNo;
    Student(std::string n, int a, int r) : Person(n, a), rollNo(r) {}

    void getInfo() {
        std::cout << "Name : " << name << std::endl;
        std::cout << "Age : " << age << std::endl;
        std::cout << "Roll No : " << rollNo << std::endl;
    }
};

int main(int argc, const char* argv[]) {
    Student("Goofupp", 27, 1001).getInfo();  // does any memory also created here ?? how to understand this behaviour

    Student rahul("Rahul", 23, 1002);  // there is block of memory allocated for rahul

    rahul.getInfo();

    return 0;
}

I was expecting error saying "declaration does not define anything" thing like we get when we define like below

int main()
{
  int;     
  cout<<"hello\n";     
  return 0; 
}

Solution

  • This line

    Student("Goofupp", 27, 1001).getInfo();
    

    calls the constructor to create an instance of Student. Its a temporary object that ceases to exist after the ; and it has no name. Because it stays alive until the ; you can call a method.

    In the code below unfortunately I didn't create[...] any object [...]

    You do create a temporary object.

    In the code below unfortunately I didn't [...]name any object [...]

    Temporary objects don't need a name. There is no need for a name because anyhow you cannot refer to the object after its lifetime ended.

    I was expecting error saying "declaration does not define anything"

    There is no such error, because the line is not a declaration.