Deal of The Day! Hurry Up, Grab the Special Discount - Save 25% - Ends In 00:00:00 Coupon code: SAVE25
Welcome to Pass4Success

- Free Preparation Discussions

C++ Institute Exam CPA Topic 7 Question 84 Discussion

Actual exam question for C++ Institute's CPA - C++ Certified Associate Programmer exam
Question #: 84
Topic #: 7
[All CPA - C++ Certified Associate Programmer Questions]

What happens when you attempt to compile and run the following code?

#include

using namespace std;

class A {

public :

void print() {

cout << "A ";

}

};

class B {

public :

void print() {

cout << "B ";

}

};

int main() {

B sc[2];

B *bc = (B*)sc;

for (int i=0; i<2;i++)

(bc++)->print();

return 0;

}

Show Suggested Answer Hide Answer
Suggested Answer: B

Contribute your Thoughts:

Shenika
2 days ago
I think it prints: A B
upvoted 0 times
...
Luann
24 days ago
You know, I'm starting to wonder if the answer is actually D) B A. Think about it - we're casting the sc array to a B* pointer, but the underlying objects are actually A objects. So when we call print() on the B* pointer, it should invoke the print() function of the A class, right? Hmm, I'm not totally sure, but that's my best guess.
upvoted 0 times
...
Gladys
26 days ago
Haha, I bet the exam writers are just trying to trip us up with this one. They're probably hoping we'll overthink it and second-guess ourselves. I'm just going to go with my gut and say it prints B B. What could be simpler than that?
upvoted 0 times
...
Shawnna
27 days ago
Hold on, I'm not so sure about that. If the objects are actually A objects, shouldn't it be printing A A? Or maybe it's going to print A B since we're accessing the objects through a B* pointer? This is really confusing, I need to think this through more carefully.
upvoted 0 times
...
Katie
28 days ago
I think the key here is the casting of the sc array to a B* pointer. Since we're calling print() on the B* pointer, it's going to invoke the print() function of the B class, even though the underlying objects are actually A objects. So my guess is that it's going to print B B.
upvoted 0 times
...
Vicky
30 days ago
Okay, let's take a closer look at this. We've got two classes, A and B, both with a print() function that prints out their respective letters. Then in the main function, we create an array of B objects and cast it to a B* pointer. Finally, we loop through and call the print() function on each element. Hmm, this is tricky.
upvoted 0 times
...
Wayne
1 months ago
Whoa, this question looks like a real mindbender! I'm not even sure what's going to happen when I run this code. Is it going to print A A, B B, A B, or B A? My brain is already starting to hurt just thinking about it.
upvoted 0 times
...

Save Cancel