I have a class that has only one function “Print()” and two properties “age, sex”. And i am trying to understand when is object creating on memory?
i can always access to object’s props and functions even i didn’t call it’s constructor function.
Isn’t there any rule for the creating object from the class?
In C# this won’t create object on memory: ClassName cls;
But this will create: ClassName cls = new ClassName();
In C++ is there any way to not create object in memory until i need to call it’s constructor function?
#include <QtCore/QCoreApplication>
#include "iostream"
using namespace std;
class ClassName{
public:
void print(){
cout<< "Age: " <<age <<endl;
cout<< "Sex: " <<sex <<endl;
}
int age;
char sex;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ClassName *ex1 = new ClassName();
ex1->print();
ClassName ex2;
ex2.print();
ClassName ex3= {10,'e'};
ex3.print();
ClassName exCopy(ex3);
exCopy.print();
return a.exec();
}
The equivalent to your C# example, using C++, is as follows:
C# classes are ‘reference’ types, which are like C++ ‘pointer’ types.