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<<"hellon";
return 0;
}
2
Answers
This line
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.You do create a temporary 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.
There is no such error, because the line is not a declaration.
Its because we can explicitly call constructors of a class. That’s why the line :
worked correctly.
The logic is very simple. It just first calls the relevent constructor, in your case, it was :
Memory for object was allocated due to call to its constructor. Then on that object, you called the method getInfo(). getInfo() gives some prints some output and then the function ends. The object wasn’t stored anywhere so it goes out of scope and got destroyed by destructor after that line.
The anwser to your 2nd question is that this was temporary, so you can’t use it later in the code. To use this, you can name it, assign to another Student object or maybe pass to another function: