0
0
C++programming~10 mins

Encapsulation best practices in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a private member variable in a class.

C++
class Person {
private:
    int [1];
};
Drag options to blanks, or click blank then click option'
Apublic
Bage
CgetAge
Dvoid
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using access specifiers like 'public' as variable names.
2fill in blank
medium

Complete the code to define a public getter method for the private variable.

C++
class Person {
private:
    int age;
public:
    int [1]() {
        return age;
    }
};
Drag options to blanks, or click blank then click option'
AgetAge
BsetAge
Cage
DPerson
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Naming the getter method the same as the variable.
3fill in blank
hard

Fix the error in the setter method to properly set the private variable.

C++
class Person {
private:
    int age;
public:
    void setAge(int [1]) {
        age = [1];
    }
};
Drag options to blanks, or click blank then click option'
Avalue
Bage
Cthis
DnewAge
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the same name for parameter and member variable without 'this' pointer.
4fill in blank
hard

Fill both blanks to complete the setter method using the 'this' pointer.

C++
class Person {
private:
    int age;
public:
    void setAge(int [1]) {
        this->[2] = [1];
    }
};
Drag options to blanks, or click blank then click option'
AnewAge
Bage
Cvalue
DageValue
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Not using 'this->' causing assignment to itself.
5fill in blank
hard

Fill all three blanks to create a class with private member, public getter, and setter methods.

C++
class Car {
private:
    int [1];
public:
    int get[2]() {
        return [1];
    }
    void set[2](int value) {
        this->[1] = value;
    }
};
Drag options to blanks, or click blank then click option'
Aspeed
BSpeed
Cvelocity
DVelocity
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using inconsistent names between member and methods.