0
0
C++programming~20 mins

Class definition syntax in C++ - Practice Problems & Coding Challenges

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

int main() {
    Box b(5);
    std::cout << b.length << std::endl;
    return 0;
}
A5
B0
CCompilation error
DUndefined behavior
Attempts:
2 left
πŸ’‘ Hint
Look at how the constructor sets the length and how it's accessed.
πŸ“ Syntax
intermediate
2:00remaining
Identify the syntax error in class definition
Which option contains a syntax error in the class definition?
C++
class Person {
public
    std::string name;
    int age;
};
AMissing semicolon after class name
BMissing semicolon after public keyword
CMissing return type for constructor
DMissing curly braces around class body
Attempts:
2 left
πŸ’‘ Hint
Check the line with the access specifier.
πŸ”§ Debug
advanced
2:00remaining
Why does this class cause a compilation error?
Given the code below, why does it cause a compilation error?
C++
class Counter {
private:
    int count;
public:
    Counter() { count = 0; }
    void increment() { count++; }
};

int main() {
    Counter c;
    c.count = 5;
    c.increment();
    std::cout << c.count << std::endl;
    return 0;
}
Aincrement() is not declared as static
BMissing semicolon after class definition
CConstructor does not initialize count
Dcount is private and cannot be accessed directly outside the class
Attempts:
2 left
πŸ’‘ Hint
Check the access level of count and where it is accessed.
🧠 Conceptual
advanced
2:00remaining
Class member initialization order
What will be the output of this code?
C++
class Test {
public:
    int x;
    int y;
    Test() : y(10), x(y + 5) {}
};

int main() {
    Test t;
    std::cout << t.x << ", " << t.y << std::endl;
    return 0;
}
Ax=garbage, y=10
Bx=5, y=10
Cx=garbage value, y=10 (because x initialized before y)
DUninitialized x, y=10
Attempts:
2 left
πŸ’‘ Hint
Members are initialized in the order they are declared, not the order in initializer list.
❓ Predict Output
expert
2:00remaining
Output of class with static member
What is the output of this program?
C++
class Sample {
public:
    static int count;
    Sample() { count++; }
};

int Sample::count = 0;

int main() {
    Sample a;
    Sample b;
    Sample c;
    std::cout << Sample::count << std::endl;
    return 0;
}
A3
B0
CCompilation error due to static member
D1
Attempts:
2 left
πŸ’‘ Hint
Static members are shared across all instances.