6.096 Introduction To C++: Mit Opencourseware
6.096 Introduction To C++: Mit Opencourseware
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
Welcome to 6.096
Lecture 7
January 21, 2009
Constructors
�Objects
Ob jects need initialization to avoid the
assignment of junk values.
� No return statement.
�Never
N ever declare
declare a constructor
constructor as virtual
virtual or static,
static, const,
const,
volatile, or const volatile.
Rectangle::Rectangle() // constructor
{
height = 6;
width = 6;
}
Default constructors
// constructor
Xamol(int, int , int = 0);
// copy constructor
Xomal(const X&);
};
class Yamol {
public:
� Used:
Used:
� – When an object is created from another object of the
same type.
� – When an object is passed by value as a parameter to a
function.
� – When an object is returned from a function.
Example
class MIT
{
private:
char *name;
public:
MIT()
{
name = new char[20];
}
Called
C
• alled for
for a class
class object
object when
when that
that object
object passes out of
of scope
or is explicitly deleted.
public:
Wheat(int, char); // Constructor for class Wheat
};
Wheat:: ~Wheat()
{}
Constructor
Destructor
� When a class is inherited all the functions and data member are
inherited, although not all of them will be accessible by the
member functions of the derived class.
� Exceptions:
� – The constructor and destructor of a base class are not
inherited
� – the assignment operator is not inherited
� – the friend functions and friend classes of the base class
are also not inherited.
Access specifiers
members of the
yes yes yes
same class
members of
yes yes no
derived classes
� …
� };
� class Daughter
Daughter : p
public
ublic Mother
� {
....
};
class MIT void output()
{ {
public: MIT::output();
MIT() { x=0; } cout << s1 << '\n';
void func(int n1) { x = n1*5; } }
void output() { cout << x << '\n';
'\n'; }
private:
private: int s1;
int x; };
};
int main()
class IAP : public MIT {
{ IAP obj;
obj.func(10);
public:
p ublic:
obj.output();
obj.output();
IAP() { s1=0; } obj.func1(20);
obj.output();
void func1(int n1) }
{
s1=n1*10; 0 50
50 200
}
Multiple inheritance
� Inheriting from more than one class
A B C