Sunday, February 13, 2011

What is constructor?

What is constructor?

A constructor is a class function with the same name as the class itself. It cannot have a return type and may accept parameters. It will be called after the memory allocation to the member variables. Constructor is used to set initial values to members variables.


Example:

 

#include <iostream>
#include <string>
#include <conio.h>
using namespace std;

class Student
{
public:
     Student()
     {
          m_nAge=0;
          strcpy(m_szName,"");
     };    
     int m_nAge;
     char m_szName[20];
};

int main()
{
     Student obj;
     cout<<"Name: "<<obj.m_szName<<"\r\n"<<"Age: "<< obj.m_nAge<<"\r\n";
     getch();
     return 0;
}



Result:
Name:
Age: 0

Difference between C and C++?

Difference between C and C++?
C is a structured programming language. C++ is object oriented programming language.

Programmers use functions/procedures to deal with larger program in C language. In C++ programmers construct a class and related member functions to deal with large class functionality.

C++ can have member functions of structures/classes. C does not support modularization of member functions.

C++ can hide/abstract member variables/functions by private or protected keyword. In C language structure members can not be hidden from outside world. C never support abstraction.

C++ has function and operator overloading/polymorphism feature. C language does not have polymorphism features.

C also does not support inheritance.