0
0
C++programming~20 mins

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

Choose your learning style9 modes available
Default Constructor in C++
πŸ“– Scenario: Imagine you are creating a simple program to represent a book in a library. Each book has a title and a number of pages. You want to create a class to hold this information and learn how to use a default constructor to set initial values.
🎯 Goal: Build a C++ class called Book with a default constructor that sets the title to "Unknown" and pages to 0. Then create an object of this class and print its details.
πŸ“‹ What You'll Learn
Create a class named Book
Add two member variables: title (string) and pages (int)
Write a default constructor that sets title to "Unknown" and pages to 0
Create an object of Book using the default constructor
Print the title and pages of the object
πŸ’‘ Why This Matters
🌍 Real World
Default constructors help create objects with safe starting values, useful in many programs like managing library books or user profiles.
πŸ’Ό Career
Understanding constructors is essential for C++ programming jobs, especially in software development and systems programming.
Progress0 / 4 steps
1
Create the Book class with member variables
Write a class called Book with two public member variables: title of type std::string and pages of type int.
C++
Need a hint?

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

2
Add a default constructor to Book
Inside the Book class, add a default constructor named Book() that sets title to "Unknown" and pages to 0.
C++
Need a hint?

Write a constructor like Book() { title = "Unknown"; pages = 0; }.

3
Create a Book object using the default constructor
In the main() function, create an object named myBook of type Book using the default constructor.
C++
Need a hint?

Write Book myBook; inside main().

4
Print the title and pages of myBook
Add code in main() to print the title and pages of the myBook object. Use std::cout to print exactly: Title: Unknown and Pages: 0 on separate lines.
C++
Need a hint?

Use std::cout << "Title: " << myBook.title << std::endl; and similarly for pages.