0
0
C++programming~20 mins

Data members and member functions in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Data Members and Member Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of member function modifying data member
What is the output of this C++ program?
C++
class Counter {
public:
    int count = 0;
    void increment() {
        count++;
    }
};

int main() {
    Counter c;
    c.increment();
    c.increment();
    std::cout << c.count << std::endl;
    return 0;
}
A2
B0
C1
DCompilation error
Attempts:
2 left
πŸ’‘ Hint
The increment function increases the count by one each time it is called.
❓ Predict Output
intermediate
2:00remaining
Output of const member function accessing data member
What will this program print?
C++
class Box {
    int length = 5;
public:
    int getLength() const {
        return length;
    }
};

int main() {
    Box b;
    std::cout << b.getLength() << std::endl;
    return 0;
}
A5
B0
CCompilation error due to const function
DUndefined behavior
Attempts:
2 left
πŸ’‘ Hint
Const member functions can read data members but cannot modify them.
❓ Predict Output
advanced
2:00remaining
Output when accessing private data member directly
What happens when you try to compile and run this code?
C++
class Sample {
private:
    int value = 10;
public:
    int getValue() {
        return value;
    }
};

int main() {
    Sample s;
    std::cout << s.value << std::endl;
    return 0;
}
A10
BRuntime error
C0
DCompilation error: 'value' is private
Attempts:
2 left
πŸ’‘ Hint
Private members cannot be accessed directly outside the class.
❓ Predict Output
advanced
2:00remaining
Output of static data member shared across objects
What is the output of this program?
C++
class Tracker {
public:
    static int count;
    Tracker() { count++; }
};

int Tracker::count = 0;

int main() {
    Tracker t1;
    Tracker t2;
    Tracker t3;
    std::cout << Tracker::count << std::endl;
    return 0;
}
A0
B3
C1
DCompilation error due to static member
Attempts:
2 left
πŸ’‘ Hint
Static members are shared by all objects of the class.
🧠 Conceptual
expert
2:00remaining
Effect of const member function on data members
Which statement is true about const member functions in C++?
AThey cannot access any data members of the class.
BThey can modify any data member of the class.
CThey can modify data members marked as mutable.
DThey can only be called on non-const objects.
Attempts:
2 left
πŸ’‘ Hint
Const member functions promise not to change the object except for mutable members.