Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   const and non const parameter passing (http://www.velocityreviews.com/forums/t806019-const-and-non-const-parameter-passing.html)

asit 11-17-2011 10:17 AM

const and non const parameter passing
 
why the following code does not compile at line 14

#include <iostream>
#include <cstdlib>

using namespace std;

struct One
{
void funct1()
{
cout<<"Testing..."<<endl;
}
};

void funct2( const One& c) //line 14
{
c.funct1();
}

int main()
{
One b;
funct2(b);
return 0;
}

asit 11-17-2011 10:20 AM

Re: const and non const parameter passing
 
sorry...the error is at line 16

Ian Collins 11-17-2011 10:24 AM

Re: const and non const parameter passing
 
On 11/17/11 11:17 PM, asit wrote:
> why the following code does not compile at line 14
>
> #include<iostream>
> #include<cstdlib>
>
> using namespace std;
>
> struct One
> {
> void funct1()
> {
> cout<<"Testing..."<<endl;
> }
> };
>
> void funct2( const One& c) //line 14
> {
> c.funct1();


It will fail here. funct1() is a non-const member function, c is a const
object.

--
Ian Collins

Juha Nieminen 11-17-2011 05:09 PM

Re: const and non const parameter passing
 
asit <lipun4u@gmail.com> wrote:
> using namespace std;


You wrote 20 characters (and a couple of newlines) in order
to save writing 5 characters (namely "std::") twice. Overall the
size of your program increased by 12 characters and two lines
without any obvious benefit (such as the program becoming easier
to read and understand). Was it really worth it?

> struct One
> {
> void funct1()
> {
> cout<<"Testing..."<<endl;
> }
> };
>
> void funct2( const One& c) //line 14
> {
> c.funct1();
> }


funct1() must be const if you want to call it using a const
object.


All times are GMT. The time now is 03:10 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.