Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Initialization List Practice | Constructors and Destructors
C++ OOP

book
Initialization List Practice

Task

Swipe to start coding

  • Rewrite constructor using the initialization list instead of assignment statements in the constructor body.
  • Ensure that the order of initialization matches the order of declaration for the class member variables.

Solution

cpp

solution

#include <iostream>

class Rectangle {
public:
Rectangle(float _length, float _width, float scale = 1)
:length(_length * scale), width(_width * scale), area(length * width) { }

float length, width, area;
};

int main()
{
Rectangle rect(2, 4, 1.5);
std::cout << rect.area;
}
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 4
#include <iostream>

class Rectangle {
public:
Rectangle(float _length, float _width, float scale = 1)
{
length = _length * scale;
width = _width * scale;
area = length * width;
}

float length, area, width;
};

int main()
{
Rectangle rect(2, 4, 1.5);
std::cout << rect.area;
}

Ask AI

expand
ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt