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

Trying to access private class variables in header function

I need several functions in a header file that use std::cout to say the date, but I don’t know how to access them from the header file. If I were within the class, I could just say something like:

 void  DisplayStandard()
    {
        cout << month << "/" << day << "/" << year << endl;
    }

However, since I’m accessing month, day, and year (which are privates in my .cpp file) I’m not sure how to modify those from void functions in the implementation file. Here’s all the code:

dateclasses.h

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

#ifndef DATECLASS_H
#define DATECLASS_H

class dateclass
{
    private:
        int month;
        int day;
        int year;
    public:
        //default constructor
        dateclass()
        {
            month = 1;
            day = 1;
            year = 1;
        }
        //value constructor
        dateclass(int month, int day, int year) 
        {
            this->month = month;
            this->day = day;
            this->year = year;
        }
        void DisplayStandard(); 
    
};
#endif

dateclasses.cpp

#include "dateclass.h"
#include <iostream>

using namespace std;

void DisplayStandard()
{
    cout << "Date: " << month << "/" << day << "/" << year << endl;
}   

I have yet to set up the main function, though I don’t think it necessary for this

>Solution :

You can solve this by changing void DisplayStandard() to void dateclass::DisplayStandard() as shown below

void dateclass::DisplayStandard()//note the dateclass:: added infront of DisplayStandard
{
    cout << "Date: " << month << "/" << day << "/" << year << endl;
} 
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