VC++ tutorial

Visual C++ Examples

How To Add Menu In VC++

adplus-dvertising
Construtors In VC++
Previous Home Next

Constructor is special type of member function. member function having same name as it's class. Constructor are used to initialize the instance variable of an object. Construction declaration looks like method declaration. Constructor is not execute the return type value. Constructor is automatically called when object is creating.

#include <iostream>
using namespace std;
class Book;
{
    char BN,BW;
    public:
    {
        BN = java
        WN = ABC
        cout<<"\n Book name is";
        }
        void display()
        {
            cout<<"\n Book details:"<<java"<<ABC;
        }
};
int main()
{
Book obj (c++, xyz);
Book obj2;
obj.display();
obj2.display();
return 0;
}
Types Of Constructor:

Default Constructor: A Default constructor is the constructor which doesn't take any argument it has no parameter. if no constructor is defined then the compiler produce the default constructor

#include <iostream>
using namespace std;
class Book
{
public:
int p;
int id;
Book(){p=id=1;}
};
int main()
{
Book Book1;
cout << "Default constructs p,id value::"<<
Book1.p <<" , "<< Book1.id << "\n";
return 0;
} 

Parameterized Constructor: A constructor that receives argument, parameter is called a parameterized constructor. This is achieved by passing arguments to the constructor function when the objects are created.

#include <iostream>
using namespace std;
class Book {
  int p, id;
public:
  Book(int k, int l) {
     p=k; 
     id=l;
  }
     
  void show() {
     cout << p << " " << id;
  }
};
int main()
{
  Book ob(3, 5);
  ob.show();
  return 0;
}

Copy Constructor: A copy constructor is a member function which initializes an object using another object of the same class. The copy constructor is a special kind of constructor which creates a new object which is a copy of an existing one, and does it efficiently.

#include<iostream>
using namespace std;
 
class Book
{
private:
    int p, id;
public:
    Book(int p1, int id1) { p = p1; id = id1; }
 
  
    Book(const Book &Lia) {p = Lia.p; id = Lia.id; }
 
    int getp()            {  return p; }
    int getid()            {  return id; }
};
 
int main()
{
    Book p1(1000,1002); 
    Book Lia = p1;
 
    
    cout << "p1.p = " << p1.getp() << ", id1.id = " << p1.getid();
    cout << "\nLia.p = " <<Lia.getp() << ", Lia.id = " << Lia.getid();
 
    return 0;
}
Previous Home Next