const and non const parameter passing

Discussion in 'C++' started by asit, Nov 17, 2011.

  1. asit

    asit Guest

    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, Nov 17, 2011
    #1
    1. Advertising

  2. asit

    asit Guest

    sorry...the error is at line 16
     
    asit, Nov 17, 2011
    #2
    1. Advertising

  3. asit

    Ian Collins Guest

    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
     
    Ian Collins, Nov 17, 2011
    #3
  4. asit <> 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.
     
    Juha Nieminen, Nov 17, 2011
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Victor Bazarov
    Replies:
    25
    Views:
    965
    E. Robert Tisdale
    Mar 23, 2005
  2. Mark Stijnman
    Replies:
    2
    Views:
    512
    =?ISO-8859-15?Q?Juli=E1n?= Albo
    Apr 22, 2005
  3. Javier
    Replies:
    2
    Views:
    621
    James Kanze
    Sep 4, 2007
  4. fungus
    Replies:
    13
    Views:
    946
    fungus
    Oct 31, 2008
  5. Old Wolf

    Same pointer parameter const and non-const

    Old Wolf, Nov 3, 2009, in forum: C Programming
    Replies:
    3
    Views:
    556
    Ben Bacarisse
    Nov 4, 2009
Loading...

Share This Page