0
0
C++programming~30 mins

Parameterized constructor in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Parameterized constructor
πŸ“– Scenario: Imagine you are creating a simple program to store information about books in a library. Each book has a title and a number of pages.
🎯 Goal: You will create a class called Book with a parameterized constructor to set the title and number of pages when creating a new book object.
πŸ“‹ What You'll Learn
Create a class named Book
Add a parameterized constructor to Book that takes title and pages
Store the title and pages in member variables
Create a printDetails method to display the book's title and pages
Create a Book object with title "C++ Basics" and pages 250
Call printDetails to show the book information
πŸ’‘ Why This Matters
🌍 Real World
Classes with parameterized constructors are used to create objects with specific initial data, like books in a library system.
πŸ’Ό Career
Understanding constructors is essential for object-oriented programming jobs, enabling you to build flexible and reusable code.
Progress0 / 4 steps
1
Create the Book class with member variables
Create a class called Book with two private member variables: title of type std::string and pages of type int.
C++
Need a hint?

Use class Book { private: std::string title; int pages; }; to define the class and variables.

2
Add a parameterized constructor to Book
Add a public parameterized constructor to the Book class that takes std::string title and int pages as parameters and sets the member variables accordingly.
C++
Need a hint?

Use Book(std::string title, int pages) { this->title = title; this->pages = pages; } inside the class.

3
Add a method to print book details
Add a public method called printDetails to the Book class that prints the book's title and number of pages in the format: Title: [title], Pages: [pages].
C++
Need a hint?

Define void printDetails() { std::cout << "Title: " << title << ", Pages: " << pages << std::endl; }.

4
Create a Book object and print details
In main(), create a Book object named myBook using the parameterized constructor with title "C++ Basics" and pages 250. Then call myBook.printDetails() to display the book information.
C++
Need a hint?

Create the object with Book myBook("C++ Basics", 250); and call myBook.printDetails();.