0
0
C++programming~10 mins

Access specifiers 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 make the member variable accessible only within the class.

C++
class MyClass {
private:
    int [1];
};
Drag options to blanks, or click blank then click option'
Adata
Bvalue
Cnumber
Dcount
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using reserved keywords as variable names
Leaving the variable name blank
2fill in blank
medium

Complete the code to declare a public member function that returns the private variable.

C++
class MyClass {
private:
    int value;
public:
    int [1]() {
        return value;
    }
};
Drag options to blanks, or click blank then click option'
AreturnValue
BsetValue
Cvalue
DgetValue
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using a setter name for a getter function
Using the variable name as function name
3fill in blank
hard

Fix the error in the code by choosing the correct access specifier to allow derived classes to access the base class member.

C++
class Base {
[1]:
    int protectedVar;
};

class Derived : public Base {
public:
    void show() {
        std::cout << protectedVar << std::endl;
    }
};
Drag options to blanks, or click blank then click option'
Aprotected
Bpublic
Cinternal
Dprivate
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using private instead of protected
Using internal which is not a C++ specifier
4fill in blank
hard

Fill both blanks to declare a class with a private variable and a public setter function.

C++
class Sample {
[1]:
    int data;
[2]:
    void setData(int d) {
        data = d;
    }
};
Drag options to blanks, or click blank then click option'
Aprivate
Bprotected
Cpublic
Dinternal
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Making variables public
Using protected for the setter function
5fill in blank
hard

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

C++
class Data {
[1]:
    int value;
[2]:
    int getValue() {
        return value;
    }
[3]:
    void setValue(int v) {
        value = v;
    }
};
Drag options to blanks, or click blank then click option'
Aprivate
Bpublic
Cprotected
Dinternal
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Making setter public
Making variable public