Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading