Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Attributes of the Class | Fundamentals of OOP in C++
C++ OOP
Section 1. Chapter 4
single

single

bookChallenge: Attributes of the Class

Swipe to show menu

syntax.h

syntax.h

copy
1234
class Name { public: Type AttributeName; };

Public attributes and methods in a class can be directly accessed using the dot operator (.) on an object of the class.

main.cpp

main.cpp

copy
12345678910111213
class Student { public: int age; }; int main() { Student bob; Student ann; bob.age = 25; ann.age = 33; }
Note
Note

The public keyword makes class members accessible from outside the class, which is why it's used here. This concept will be explained in more detail later.

Task

Swipe to start coding

Imagine you are building a simple registration system. You need to create a User class with fields for the user's name, age, and a boolean indicating whether the user is an adult. Your task is to implement a function that creates a User object, checks if the user is at least 18 years old, and sets the boolean field accordingly.

  1. Define a class User with three fields:

    • name of type std::string
    • age of type int
    • isAdult of type bool
  2. Implement a function registerUser that takes a name and age as parameters:

    • Create a User object inside the function.
    • Assign the passed name and age to the object's corresponding fields.
    • Initialize isAdult to false.
    • Check the age: if age is 18 or older, set isAdult to true.
    • Return the created User object.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 4
single

single

Ask AI

expand

Ask AI

ChatGPT

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

some-alt