Johnny5001
Johnny5001

Reputation: 1

C++ Protected member access

need a protected class made to access month day year I understand you need to create a class from the inherited class and not call the protected data in main

#include <iostream>
#include <fstream>

using namespace std;

class dateType
{
   public:
      dateType();
      dateType(int, int, int);
      void setDate(int, int, int);
      void printDate(ostream&)const; 


   protected:
      int month;
      int day;
      int year;
};

ostream& operator<<(ostream &os, const dateType &d) {
   os << d.month << "/" << d.day << "/" << d.year; 
   files 

      return os;
} 

when this code executes I get an error saying month, day and year are protected

Upvotes: 0

Views: 55

Answers (2)

Иван Петров
Иван Петров

Reputation: 11

Code with friend operator <<.

#include <iostream>
#include <fstream>

using namespace std;

class dateType
{
public:
    dateType();
    dateType(int, int, int);
    void setDate(int, int, int);
    void printDate(ostream&)const;

    friend ostream& operator<<(ostream &os, const dateType &d) {
        os << d.month << "/" << d.day << "/" << d.year;
        return os;
    }


protected:
    int month;
    int day;
    int year;
};

Upvotes: 1

M.Cuijl
M.Cuijl

Reputation: 53

Your method should be friend like this:

friend ostream& operator<<(ostream &os, const dateType &d) 
{
    os << d.getMonth() << "/" << d.getDay() << "/" << d.getYear();
    return os;
}

In your class implementation

Upvotes: 0

Related Questions