Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a base class pointer.
C++
Base* [1]; Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using a variable name that is not a pointer.
Forgetting the asterisk (*) to declare a pointer.
β Incorrect
The pointer to the base class is declared as 'basePtr' here, which is a common naming convention.
2fill in blank
mediumComplete 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Assigning the object itself instead of its address.
Using the pointer variable name instead of the object.
β Incorrect
We assign the address of the derived object 'd' to the base class pointer using '&d'.
3fill in blank
hardFix 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'
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.
β Incorrect
The base class pointer can only call functions declared in the base class, so 'baseFunction' is correct.
4fill in blank
hardFill 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'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using different pointer names in declaration and call.
Calling non-virtual functions expecting polymorphic behavior.
β Incorrect
The pointer 'basePtr' is used to point to the derived object and call the virtual function correctly.
5fill in blank
hardFill 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'
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.
β Incorrect
Deleting the object through the base class pointer 'basePtr' and setting it to nullptr prevents memory leaks.