0
0
C++programming~20 mins

Creating objects in C++ - Practice Exercises

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

int main() {
    Box b(10);
    std::cout << b.length << std::endl;
    return 0;
}
A0
BRuntime error
CCompilation error
D10
Attempts:
2 left
πŸ’‘ Hint
Look at how the constructor initializes the length member.
❓ Predict Output
intermediate
2:00remaining
Output when creating an object with default constructor
What will be the output of this code snippet?
C++
class Point {
public:
    int x, y;
    Point() { x = 5; y = 7; }
};

int main() {
    Point p;
    std::cout << p.x << "," << p.y << std::endl;
    return 0;
}
ACompilation error
B0,0
C5,7
DGarbage values
Attempts:
2 left
πŸ’‘ Hint
The default constructor sets x and y explicitly.
❓ Predict Output
advanced
2:00remaining
Output of object creation with private constructor
What happens when you try to compile and run this code?
C++
class Secret {
private:
    Secret() {}
public:
    static Secret create() { return Secret(); }
};

int main() {
    Secret s = Secret::create();
    return 0;
}
ACompiles and runs without output
BCompilation error: constructor is private
CRuntime error
DLinker error
Attempts:
2 left
πŸ’‘ Hint
The static method can access the private constructor.
❓ Predict Output
advanced
2:00remaining
Output of object creation with deleted copy constructor
What will happen when this code is compiled and run?
C++
class NoCopy {
public:
    NoCopy() {}
    NoCopy(const NoCopy&) = delete;
};

int main() {
    NoCopy a;
    NoCopy b = a;
    return 0;
}
ARuns and copies object
BCompilation error due to deleted copy constructor
CRuntime error
DLinker error
Attempts:
2 left
πŸ’‘ Hint
Copying is disabled explicitly.
🧠 Conceptual
expert
2:00remaining
Number of objects created in this code
How many objects are created in total when this code runs?
C++
class Sample {
public:
    Sample() {}
};

Sample createSample() {
    Sample s;
    return s;
}

int main() {
    Sample a = createSample();
    return 0;
}
A2
B1
C3
D0
Attempts:
2 left
πŸ’‘ Hint
Consider the local object and the returned object.