[SOLVED] How to call a function with the same name within another class?

Issue

This Content is from Stack Overflow. Question asked by Jasmine

I have two classes, a Card class and Deck class. Both have display() functions, and I cannot change the name of the function. I am unsure of how I can call Card::display() inside of Deck::display().

Card.cpp

void Card::display( ) const
{
   cout << rank << suit;
}

Deck.cpp //in Deck.h I did #include “Card.h”, I did not have Deck inherit
because Deck did not need to access the private member variables of Card (aka suit and rank)

void Deck::display( ) const 
{
    for (int i = 0; i < 52; i++) 
    {
       if (i % 13 == 0 && i != 0)
       {
          cout << "n";
          deck[i].display(); <--//deck is an array of 52 Cards, each index consists of
                            // a rank and a suit; here I am trying
                            //to display the entire deck of cards 4 by 13 2d array
                            //hence why I want to call the display function from class
                            // Card
       }
       else
       {
        deck[i].display() <--
       }
    }
}

So that when the display function from Deck is called from the main.cpp
it will look like (for example, if the cards are in order):

AS 2S 3S 4S 5S 6S 7S ... (all the way until King of Spades) KS //new line, new row
AH ...(all the way until King of Hearts) KH  //new line, next row    
AD ...(all the way until King of Diamonds) KD   //new line, next row 
AC ...(all the way until King of Clubs) KC  

Because the Card::display function (from code snippet above) displays
the rank then suit, and Deck::display would display the entire deck of cards.
I have been trying to do my own research online to no avail, so I would appreciate the help, thank you!



Solution

If deck is an array of Cards(as you mentioned), than when you write:

deck[i].display()

This display function will be implicit the display function of your Card class, so your code should be fine


This Question was asked in StackOverflow by Jasmine and Answered by Gabriel It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?