Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how can I assign a const function to a const member function of class
similar to the following example:

What I have tried:

<pre>class test
{
	test();
	const int y1(char i)	
	{
		cout<< i;
	}
}
const int y2(char i);
test::test()
{
	y2(char i) = &y1;
}
Posted
Updated 24-Nov-18 4:46am

Since your y1 doesn't access any member of the test then you may modify it to be static and write
C++
#include <iostream>
using namespace std;

const void (*y2)(char i);

class test
{
  static const void  y1(char i)
  {
    cout << i << "\n";
  }

public:
  test();
};

test::test()
{
  y2 = &y1;
}

int main()
{
  test t;
  y2('F');
}


The corresponding code for an ordinary (non static) method would be
C++
#include <iostream>
using namespace std;

class test;

const void (test::*y2)(char i);

class test
{
  const void  y1(char i)
  {
    cout << i << "\n";
  }

public:
  test();
};

test::test()
{
  y2 = &test::y1;
}

int main()
{
  test t;
  (t.*y2)('F');
}


Please note, in both cases the code, though working, is pretty meaningless.
 
Share this answer
 
That code does not make much sense. You have declared y1 as const int, but it does not return anything. In your test constructor you are trying to make an assignment to a non-assignable name. You would need to make y2 a function pointer to achieve what you want.
 
Share this answer
 
You cannot provide a function of the left hand side of an assignment: it is not a modifiable lvalue unless the function returns a reference:
Lvalues of the following object types are not modifiable lvalues:
An array type
An incomplete type
A const-qualified type
A structure or union type with one of its members qualified as a const type

Because these lvalues are not modifiable, they cannot appear on the left side of an assignment statement
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900