Cannont convert 'this' pointer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#ifndef DAYOFYEAR_H
#define DAYOFYEAR_H
#include <string>

class DayOfYear
{
	private:
		//Member variables
		static const std::string strMonths[12];
		static const int numOfDays[];
		std::string month;
		int day;

		//Functions
		void setMonth(std::string);
		int calcNum() const;

	public:
		//Constructors
		DayOfYear();
		DayOfYear(int );
		DayOfYear(std::string, int);

		//Functions
		std::string strPrintDate();
		int strPrintNum();
		int findMonth();
};

#endif 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
#include <sstream>
#include "DayOfYear.h"

using namespace std;


void DayOfYear::setMonth(string mon)
{
	month = mon;
}

int DayOfYear::calcNum() const
{
	setMonth("March"); //Why do you hate me 
	int num = 0;
	/*
	int count = 0;
	string comp = strMonths[count];
	string input;
	

	while(month != strMonths[count])
	{
		count++;
		if(count >11)
		{
			cout << "The month you entered doesn't exist\nPlease reenter: ";
			getline(cin, input);
			setMonth(input);
			count = 0;
		}
	}

	cout << "count is : " << count << endl;
	*/

	return num;
}


When I call setMonth, I get a compile time error of:

'DayOfYear::setMonth' : cannot convert 'this' pointer from 'const DayOfYear' to 'DayOfYear &'


Most of the fixes I saw for this error meant making your function const but setMonth cannot be const because it's changing the value of the month field. What am I doing wrong?
DayOfYear::calcNum() is a method that may take a const DayOfYear as implicit parameter for the this pointer, but DayOfYear::setMonth() may not. You'll have to make DayOfYear::calcNum() non-const.
That is because the calcNum function is not telling the truth. It says it
is a const function and won't change the object, but it trying to cheat by calling
the function setMonth function which can change the object.

In other words, calcnum was called with the this pointer pointing
to a constant DayOfYear object, but setMonth needs a pointer to a non constant DayOfYear object - hence the error.
Aww man, I should have seen that. Makes perfect sense now that I think about it. Thanks for the explanation and clarification.
Topic archived. No new replies allowed.