Introducing 

Prezi AI.

Your new presentation assistant.

Refine, enhance, and tailor your content, source relevant images, and edit visuals quicker than ever before.

Loading…
Transcript

Object Oriented Programming. C++

Lab-2

3 ways to initialize variables.

  • By using objects to assign values to variables (Data Member).

Reasons for going to constructor.

  • By using function to assign values to variables.
  • By using constructor.

3 Ways

1st Way

2nd Way

3rd way.

3rd Way

Using Constructor

Constructor

  • Initializes an object of a class.
  • Special member function that has no return type.

Constructor

  • Compiler calls the constructor whenever object is created.

How constructors are different from a normal member function?

  • Constructor has same name as the class itself.
  • Constructors don’t have return type.

How

  • Constructor is automatically called when an object is created.

Types of constructors.

1. Default Constructor.

  • It has no parameters.

  • Even if we do not define a constructor explicitly, the compiler will provide a default constructor.

Types

2. Parametrized Constructor.

  • It has some parameters.

  • Using this Constructor you can provide different values to data members of different objects

When

to use default vs parameterized

When to use default constructor vs parametrized constructor.

  • Use parametrized constructor when you want to initialize different values to different object.

  • if you want to initialize same values/data to every single object than use default constructor to initialize values to data member.

Implementation Time.

Implementation

1. Create a class Student having following data members

  • String name.
  • String department.
  • Int roll_number.

2. Now create a member function named Display() to print values of data member onto screen.

3. Create 2 objects of your own choice and initialize them using constructor.

Eye openers

Kepler's Planet resembles Earth.

1

2

587 Light year's away from Earth.

3

2 X size of Earth.

Constructor overloading

  • Constructor overloading is a concept of having more then one constructor.

Overloading

  • Each constructor will have different set of parameters.
  • Compiler calls the specific constructor based on number and type of parameter.
Learn more about creating dynamic, engaging presentations with Prezi