Sharp Tutorial
constructor in c++

Python

Java

C

C++

HTML/CSS

Java Script

PHP

SQL

C Programs

introduction to c++

  • C++ Home
  • Introduction to C++
  • History features
  • Sample Programs
  • cout , cin , endl
  • Data type and Operators
  • if else in c++
  • loop in c++

Oops in C++

  • Object / Class
  • Constructor
  • Function & Constructor Overloading
  • Inheritance
  • Overriding

Advanced C++

  • Strings in C++
  • Exception Handling
  • Special Functions
  • C++ Programs

constructor in c++

Constructor are the special functions which have the following properties :
  1. They have the same name as the class name.
  2 They do not have any return type, not even void.
  3. No need to call them automatically, called once when object is being created.
  4. Constructor may be default or parameterized as well.
  5. Mainly used to initialize the objects.

A Constructor of a Class may be defined as below

#include<iostream>
using namespace std;
Class A
{
public:
A()
{
cout<<"Default constructor called automatically when object is created"; }
} ;

Complete program to show constructor and function calling.

#include<iostream>
using namespace std;
class Student
{
public:
int rollNo;
string name;
Student(int r, string n) // parameterized constructor
{
rollNo=r;
name=n;
}
void display()
{
cout<<"name of the student is"<<name <<endl;
cout<<"Roll No of the student is"<<rollNo;
}
};
int main()
{
int r=0;
string n;
cout<<"enter the name of the student";
cin>>n;
cout<<"enter the roll no of the student";
cin>>r;
Student s1(r,n);
s1.display();
return 0;
}

 

Above program gives the following output

Enquiry about Course

Ask your Question

Click Here

Sharp (2) Tutorials

Video/ C Introduction

Watch video in full size

Video tutorial

Follow by Email
Facebook
Facebook
fb-share-icon
YouTube
Copyright © Sharp Tutorial
Build with WordPress
Wordpress Social Share Plugin powered by Ultimatelysocial
Sharp Tutorial