0
0
C++programming~10 mins

Data hiding 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 MyClass {
private:
    int [1];
};
Drag options to blanks, or click blank then click option'
Aclass
Bpublic
Cvoid
Ddata
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using keywords like 'public' or 'void' as variable names.
Forgetting to declare the variable under 'private:'.
2fill in blank
medium

Complete the code to provide a public method that accesses the private variable.

C++
class MyClass {
private:
    int data;
public:
    int [1]() {
        return data;
    }
};
Drag options to blanks, or click blank then click option'
AgetData
BsetData
Cdata
Dprivate
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Naming the method 'setData' when it should return the value.
Using the variable name 'data' as the method name.
3fill in blank
hard

Fix the error in the code to correctly set the private variable using a public method.

C++
class MyClass {
private:
    int data;
public:
    void setData(int value) {
        [1] = value;
    }
};
Drag options to blanks, or click blank then click option'
Adata
Bvalue
CsetData
Dthis->value
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Assigning the parameter to itself like 'value = value;'.
Using 'this->value' when the private variable is named 'data'.
4fill in blank
hard

Fill both blanks to create a class with a private variable and a public getter method.

C++
class Person {
private:
    [1] age;
public:
    [2] getAge() {
        return age;
    }
};
Drag options to blanks, or click blank then click option'
Aint
Bvoid
Dfloat
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using void as the return type for a getter method.
Declaring the variable as float when it should be int.
5fill in blank
hard

Fill all three blanks to define a class with a private string variable, a setter, and a getter.

C++
class Book {
private:
    [1] title;
public:
    void [2]([3] t) {
        title = t;
    }
    std::string getTitle() {
        return title;
    }
};
Drag options to blanks, or click blank then click option'
Astd::string
BsetTitle
Dint
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using int instead of std::string for the variable or parameter.
Naming the setter method incorrectly.