JAYOTI VIDYAPEETH WOMEN’S UNIVERSITY,JAIPUR
YOUTUBE(Online Video Session Uploading Process)
Object Oriented Programming Language
Guided By: - Ramesh Kumar
Assistant Prof
DEPT OF FEM
[email protected]Constructor
• A constructor in C++ is a special method that
is automatically called when an object of a
class is created.
• To create a constructor, use the same name as
the class, followed by parentheses ():
Note: The constructor has the same name as the class, it is always public,
and it does not have any return value.
Constructor Parameters
• Constructors can also take parameters (just like regular
functions), which can be useful for setting initial values for
attributes.
• The following class have brand, model and year attributes,
and a constructor with different parameters. Inside the
constructor we set the attributes equal to the constructor
parameters (brand=x, etc). When we call the constructor (by
creating an object of the class), we pass parameters to the
constructor, which will set the value of the corresponding
attributes to the same:
Example
Conti….
• Just like functions, constructors can also be
defined outside the class. First, declare the
constructor inside the class, and then define it
outside of the class by specifying the name of
the class, followed by the scope
resolution :: operator, followed by the name
of the constructor (which is the same as the
class):
Destructor
• Destructor is a member function which destructs or deletes
an object.
• A destructor function is called automatically when the object
goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called
• Destructors have same name as the class preceded by a tilde
(~)
• Destructors don’t take any argument and don’t return
anything
Example:
class String
{
private:
char *s;
int size;
public:
String(char *); // constructor
~String(); // destructor
};
String::String(char *c)
{
size = strlen(c);
s = new char[size+1];
strcpy(s,c);
}
String::~String()
{
delete []s;
}
Continue in next lecture
Thank you
?????
NEXT….
• This session powered by Digital Version 2.0,Jayoti
Vidyapeeth Women’s University ,Jaipur
• https://youtu.be/ue_Guc6zTpo