Unit 2
Unit 2
// Definition
int A::x = 1;
int main() {
A a;
// Accessing static data member using static member function.
cout << a.increment();
}
Static member function
• Properties:
1. Static member function can have access to
only other static members declared in same
class
public:
static int func ()
{
cout << " The value of the num is: " << num << endl;
}
};
// initialize the static data member
int Note :: num = 15;
3. They do not have return types, not even void and they
cannot return values
3. Explicit call
time t1=time(3,45);
2. Implicit call : also called shorthand method
time t1(3,45);
• Constructor function can be defined as inline function.
class time
{
int hr,min;
public:
time(int hr,int min) //inline constructor
{
hour=hr;
minute=min;
}
};
Parameterized constructor program
#include <iostream> void display ()
using namespace std; {
class Professor cout<<id<<" "<<name<<"
"<<salary<<endl;
{
}
public:
};
int id;
int main(void)
string name; {
float salary; Professorp1=Professor(10,
Professor (int i, string n, float s) "Aditya", 90000);
{ Professor p2=Professor(12,
id = i; "Anu", 60000);
name = n; p1.display();
salary = s; p2.display();
return 0;
}
}
Output
Copy constructor
• A constructor can accept a reference to its own
class as a parameter which is called copy
constructor.
class time
{
-------
public:
time(time &); //copy constructor
};
• Copy Constructor is used to declare and initialize an
object from another object.
• For example the statement:
• abc c2(c1);
• would define the object c2 and at the same time
initialize it to the value of c1.
geeks()
{
Output:
// allocating memory
at run time geeks
p = new char[6];
p = "geeks";
}
void display()
{
cout << p << endl;
}
};
Multiple Constructors in a class
• We have studied three types of constructors
i.e. constructor with no argument,
parameterized constructor and copy
constructor.
time(); //no arguments
time(int,int); //two arguments
time(time &t); //copy constructor
time(int h,int m) //constr. 2
class time
{
{ hr=h;
int hr,min; min=m;
public: }
time(time &t) //constr. 3
time() //constr. 1 {
{ hr=t.hr;
hr=0; min=0; min=t.min
}
}
};
• In first constructor itself supplies value and no
values are passed by calling program
• In second function call passes values to
constructor from main().
• In third, it receives one object as an argument
In main:
• time t1; invokes first constructor and set hr
and min to zero.
• time t2(3,45); invokes second constructor and
set hr and min to 3 and 45 respectively.
• time t3(t2); invokes third constructor and
copies values of t2 to t3.
• C++ allows us to use more than one constructor
in same class.
Overloading of constructors
• When more than one constructor used in
same class, then constructors are overloaded.
Program
#include <iostream>
using namespace std;