Search code examples
c++classheader-files

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

#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;
    }