Page 1 of 1

Const in C++

Posted: Fri Sep 05, 2014 2:28 pm
by lilzz
1)Const func1 (Const ClassA&) Const
Const ClassA& means Class A is read-only. What does the left and right hand Const means?


2)ClassA<0> (handler)(error)
what does 0 means?

Re: Const in C++

Posted: Sat Sep 06, 2014 2:19 am
by danjperron
1-) I think you mean const and not "Const"

The first const tell that the function will be used when the class is const. And the one at the end tell that is a read only function.

This is an example

Code: Select all

#include <iostream>

using namespace std;

class ClassA
{
  public:
    int nValue;
    ClassA() {nValue=1;}
};

class ClassTest
{
 public:
  ClassTest() {Variable1=0;}
  const int func1(const ClassA& A) const { return A.nValue;}
  int func1(const ClassA& A)  {Variable1=2; return A.nValue;}
  int Variable1;
};




int main(void)
{

  const ClassA  MyA;
  const ClassTest MyTest;
  ClassTest MyTest2;

  cout << "=== MyTest" << endl;
  cout << "nValue = "<< MyTest.func1(MyA) << endl;
  cout << "Variable1 =" << MyTest.Variable1 << endl;
  cout << "=== MyTest2" << endl;
  cout << "nValue = "<< MyTest2.func1(MyA) << endl;
  cout << "Variable1 =" << MyTest2.Variable1 << endl;
return 0;
}
And this is the output

Code: Select all

pi@WebPi ~ $ g++ -o test test.cpp
pi@WebPi ~ $ ./test
=== MyTest
nValue = 1
Variable1 =0
=== MyTest2
nValue = 1
Variable1 =2
2-) Integer template could pass parameters

http://stackoverflow.com/questions/4991 ... int-n-mean
your example are hard to decipher since you just put one line.

I hope it helps

Daniel

Re: Const in C++

Posted: Sat Sep 20, 2014 1:42 am
by NewNewz
Can I just check, do I have to use const and not Const - does the capitalization matter? Will Const not work?

http://simplenewz.com/2014-07-29/Mainstream/feed/4459

Re: Const in C++

Posted: Sat Sep 20, 2014 12:42 pm
by danjperron
C/C++, C#, Python, Java , etc... are all case sensitive.

Const is not const unless you do something like #define Const const

ex: nano const.cpp

Code: Select all

#include <iostream>

#define Const const

const int a=2;
Const int b=3;

int  main(void)
{
  std::cout << "a =" << a << std::endl;
  std::cout << "b =" << b << std::endl;
  return 0;
}
compile it using

Code: Select all

g++ -o const const.cpp
Remove the define and try to recompile.


Daniel