A destructor can never be overloaded. An overloaded destructor would mean that the destructor has taken arguments. Since a destructor does not take arguments, it can never be overloaded.
Monday, February 14, 2011
Can destructor be overloaded?
Can destructor be overloaded?
A destructor can never be overloaded. An overloaded destructor would mean that the destructor has taken arguments. Since a destructor does not take arguments, it can never be overloaded.
A destructor can never be overloaded. An overloaded destructor would mean that the destructor has taken arguments. Since a destructor does not take arguments, it can never be overloaded.
What is destructor?
What is destructor?
A destructor is a special function member of a class that is automatically called when an object about to be deleted. It always has the same name as the class preceded by a ‘tilt’ ~ symbol and has no return type. It is used to free allocated memory used by an object. It takes no arguments.
Example:
Result:
Name: Raj
Age: 13
Memory destroyed
Name: John
Age: 12
Memory destroyed
A destructor is a special function member of a class that is automatically called when an object about to be deleted. It always has the same name as the class preceded by a ‘tilt’ ~ symbol and has no return type. It is used to free allocated memory used by an object. It takes no arguments.
Example:
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
class Student
{
public:
Student(char* szName,int nAge)
{
m_szName =new char[20];
strcpy(m_szName,szName);
m_nAge=nAge;
}
~Student()
{
delete[] m_szName;
m_szName=NULL;
cout<<"Memory destroyed \r\n";
};
int m_nAge;
char *m_szName;
};
int main()
{
{
Student obj("Raj",13);
cout<<"Name: "<<obj.m_szName<<"\r\n"<<"Age: "<< obj.m_nAge<<"\r\n";
}
Student *ptr=new Student("John",12);
cout<<"Name: "<<ptr->m_szName<<"\r\n"<<"Age: "<< ptr->m_nAge<<"\r\n";
delete ptr;
getch();
return 0;
}
Result:
Name: Raj
Age: 13
Memory destroyed
Name: John
Age: 12
Memory destroyed
What is overloaded constructor?
What is overloaded constructor?
An overloaded constructor is a constructor which takes arguments. It is also called parameterized constructor.
Example:
Result:
Name:
Age: 0
Name: John
Age: 12
An overloaded constructor is a constructor which takes arguments. It is also called parameterized constructor.
Example:
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
class Student
{
public:
Student()
{
m_nAge=0;
strcpy(m_szName,"");
};
Student(char* szName,int nAge)
{
strcpy(m_szName,szName);
m_nAge=nAge;
}
int m_nAge;
char m_szName[20];
};
int main()
{
Student obj;
cout<<"Name: "<<obj.m_szName<<"\r\n"<<"Age: "<< obj.m_nAge<<"\r\n";
Student obj2("John",12);
cout<<"Name: "<<obj2.m_szName<<"\r\n"<<"Age: "<< obj2.m_nAge<<"\r\n";
getch();
return 0;
}
Result:
Name:
Age: 0
Name: John
Age: 12
Subscribe to:
Posts (Atom)