const and non const parameter passing

A

asit

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;
}
 
I

Ian Collins

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.
 
J

Juha Nieminen

asit said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top