0
0
C++programming~10 mins

Base class pointers 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 declare a base class pointer.

C++
Base* [1];
Drag options to blanks, or click blank then click option'
AbasePtr
Bobj
Cpointer
Dptr
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using a variable name that is not a pointer.
Forgetting the asterisk (*) to declare a pointer.
2fill in blank
medium

Complete the code to assign the address of a derived class object to a base class pointer.

C++
Derived d;
Base* ptr = [1];
Drag options to blanks, or click blank then click option'
A&d
Bd
Cptr
D*d
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Assigning the object itself instead of its address.
Using the pointer variable name instead of the object.
3fill in blank
hard

Fix the error in the code to correctly call the base class function using a base class pointer.

C++
Base* ptr = new Derived();
ptr->[1]();
Drag options to blanks, or click blank then click option'
AderivedFunction
BbaseFunction
CDerivedFunction
DBaseFunction
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Trying to call a derived class specific function through a base class pointer.
Using incorrect capitalization for function names.
4fill in blank
hard

Fill both blanks to create a base class pointer that points to a derived class object and calls a virtual function.

C++
Base* [1] = new Derived();
[2]->virtualFunction();
Drag options to blanks, or click blank then click option'
Aptr
BbasePtr
CderivedPtr
DobjPtr
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using different pointer names in declaration and call.
Calling non-virtual functions expecting polymorphic behavior.
5fill in blank
hard

Fill all three blanks to correctly delete a derived class object through a base class pointer and avoid memory leaks.

C++
Base* [1] = new Derived();
// ... use the object
delete [2];
[3] = nullptr;
Drag options to blanks, or click blank then click option'
Aptr
BbasePtr
CderivedPtr
DobjPtr
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Deleting using a different pointer than the one used to allocate.
Not setting the pointer to nullptr after deletion.