0
0
C++programming~20 mins

Data hiding in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Data Hiding Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of private member access attempt
What will be the output of this C++ code?
C++
class Box {
private:
    int length;
public:
    Box(int l) : length(l) {}
};

int main() {
    Box b(10);
    // std::cout << b.length << std::endl; // Uncommenting this line
    return 0;
}
AOutputs 0
BOutputs 10
CRuntime error
DCompilation error due to private member access
Attempts:
2 left
πŸ’‘ Hint
Remember that private members cannot be accessed directly outside the class.
❓ Predict Output
intermediate
2:00remaining
Output when accessing private member via public method
What is the output of this C++ program?
C++
#include <iostream>
class Box {
private:
    int length;
public:
    Box(int l) : length(l) {}
    int getLength() { return length; }
};

int main() {
    Box b(15);
    std::cout << b.getLength() << std::endl;
    return 0;
}
A15
BRuntime error
C0
DCompilation error
Attempts:
2 left
πŸ’‘ Hint
Check how the private member is accessed.
🧠 Conceptual
advanced
1:30remaining
Why use private members in a class?
Which of the following is the main reason to declare class members as private in C++?
ATo hide internal details and protect data from unauthorized access
BTo allow direct access from outside the class
CTo make the program run faster
DTo allow inheritance from other classes
Attempts:
2 left
πŸ’‘ Hint
Think about what data hiding means.
❓ Predict Output
advanced
2:00remaining
Output of friend function accessing private member
What will be the output of this C++ code?
C++
#include <iostream>
class Box {
private:
    int length;
public:
    Box(int l) : length(l) {}
    friend int getLength(Box& b);
};

int getLength(Box& b) {
    return b.length;
}

int main() {
    Box b(20);
    std::cout << getLength(b) << std::endl;
    return 0;
}
ACompilation error due to private member access
B0
C20
DRuntime error
Attempts:
2 left
πŸ’‘ Hint
Friend functions can access private members.
❓ Predict Output
expert
2:30remaining
Value of private member after inheritance and access
What is the output of this C++ program?
C++
#include <iostream>
class Base {
private:
    int secret = 42;
public:
    int getSecret() { return secret; }
};

class Derived : public Base {
public:
    int getSecretFromDerived() {
        // return secret; // Uncommenting this line
        return getSecret();
    }
};

int main() {
    Derived d;
    std::cout << d.getSecretFromDerived() << std::endl;
    return 0;
}
ACompilation error due to private member access in Derived
B42
C0
DRuntime error
Attempts:
2 left
πŸ’‘ Hint
Private members are not accessible directly in derived classes.