A constructor that can be take arguments is called a parameterized constructor with arguments. The variables in the object are initialized by the parameter values passed through the constructor. The actual parameters present in the invocation of the constructor are assigned to the formal parameters of the constructor definition. The values passed are thus assigned to the respective data member in the object.
calss_name(arguments_list) {  }

eg: complex (int x, int y)
{
real=x;
imaginary=y;
}

Program:

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

class student
{
     private:
          char name[15];
          char rollno[9];
     public:
          student(char n[15],cahr r[9])
          {//parameterized constructor declared and defined
              strcpy(name,n);
              strcpy(rollno,r);
          }
          void putdata();
         
};
void student::putfdata()
{
     cout<<"\n Name:    "<<name;
     cout<<"\n Rollno:  "<<rollno;
}
void main()
{
     char name[15],rollno[9];
     cout<<"Enter your name :";
     cin>> name;
     cout <<"Enter your rollno:";
     cin>> rollno;
     student s(name,rollno); //obj creation and constructor invocation
     s.putdata();
     getch();

}
Note: constructor can be invoked either by an implicit call or by an explicit call.
student s = student(name. rollno);
is the explicit call for invoking the constructor.
student s(name, rollno);
Is the implicit call for invoking the constructor.


Other recommended posts of Constructor and Destructor

Posted by Unknown On 01:57 No comments

0 comments:

Post a Comment

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube

Blog Archive

Contact Us


Name

E-mail *

Message *