Top Banner
Yogi’s Guide to C++ Yogi’s Guide to C++ Default Constructor Yogendra Pal
6

Default constructors in C++

Jan 16, 2017

Download

Education

Learn By Watch
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Default constructors in C++

Yogi’s Guide to

C++Yogi’s Guide

toC++

DefaultConstructor

Yogendra Pal

Page 2: Default constructors in C++

www.learnbywatch.com | [email protected]

At the end of this tutorial you will be able to • Explain what is default constructor.

• Create default constructor.

Page 3: Default constructors in C++

www.learnbywatch.com | [email protected]

Default Constructor• A default constructor is a constructor that is used to create an object when you

don’t provide initialization values.• Time t1; //calling default constructor

• What if we do not write any constructor?• C++ automatically creates a default constructor for each class.

• It creates an uninitialized object.

• For the Time class the default constructor looks like this: • Time::Time() { }

Page 4: Default constructors in C++

www.learnbywatch.com | [email protected]

Important Thing about Default Constructor• Compiler creates a default constructor only if you don’t define any constructor.

• If you define any constructor, you need to define the default constructor too.

• If your class has non-default constructor but no default constructor then a declaration like this becomes an error.• Time t;

Page 5: Default constructors in C++

www.learnbywatch.com | [email protected]

Define Default Constructor• There are two ways to define a default constructor:

• Define a constructor with no arguments• Time();

• Provide default values for all arguments• Time(int h=12, int m=0, int s=0);

• There can be only one default constructor, so don’t use both in a class.

Page 6: Default constructors in C++

Yogi’s Guide to

C++Yogi’s Guide

toC++

Ask your questionsto learn better

Yogendra Pal

www.learnbywatch.com | [email protected]