473,714 Members | 4,906 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++ Declare main as const

5 New Member
our professor for fun decided to give us code to figure out

he declared in the main program a const class

now when i use my accessor functions, the compiler tells me:

Error 9 error C2662: 'CName::WriteFu llName' : cannot convert 'this' pointer from 'const CName' to 'CName &' c:\Users\Nick Velasco\Documen ts\Visual Studio 2005\Projects\F irst Bust\NameFun\Na meFun.cpp 67

can anyone help??
A.S.A.P please!
Aug 28 '07 #1
6 1823
463 Recognized Expert Contributor
Its hard or near impossible to decipher error messages without the affected code.

We'll need a code snipet of where the problem occurs. Please enclose the code in [ code] ... [/code]. I'm also interested in how you're using the "main" routine.
Aug 28 '07 #2
9,065 Recognized Expert Moderator Expert
If you declare a const instance of the class you are effectively saying that it's data will not changed (that is what the const keyword means).

When you call a function the compiler has to initialise the this pointer which by default for a class T is T *. Now T * points to a modifiable object but your object is const and not modifiable and this causes the compiler to output the error.

If you member function does not change any of the classes data then you can declare that member function const (the keyword goes at the end of the function declaration). In this case instead of creating this as T * the compiler creates this as const T * so you would be able to access this function from your constant object.

Of course since this is const T * the function can then not change any of the classes data members (unless they are declared mutable but I will leave you to look that up).
Aug 28 '07 #3
5 New Member
Thank you Bafa!! for the input

everything is correct our professor told us to look at the main programs and figure out from there how to make our class and header files, the rules are simple can't touch the main program

here is the main program

Expand|Select|Wrap|Line Numbers
  1. // ============================================================================
  2. // File: NameFun.cpp (Fall 2007)
  3. // ============================================================================
  4. // Study the code below to see what this program does. Then design the class
  5. // CName and implement it so this program works.
  6. //  
  7. // Sample run:
  8. //  
  9. //      nameOne = Grace Slick
  10. //      nameTwo = Grace Slick
  11. //      nameThree =
  12. //      Enter your first and last names separated by a space: Tom Sawyer
  13. //      Your name is: Tom Sawyer
  14. //  
  15. //      Testing the assignment operator...
  16. //      nameOne == Grace Slick
  17. //      nameTwo == Grace Slick
  18. //      nameThree == Grace Slick
  19. //  
  20. //      Here are the contents of the name file:
  21. //      Ingmar Bergman
  22. //      Alfred Hitchcock
  23. //      Martin Scorsese
  24. //      Federico Fellini
  25. //      Michaelangelo Antonioni
  26. //      Fritz Lang
  27. //      John Ford
  28. //  
  29. // ============================================================================
  32. #include "CName.h"
  37. // ==== main ==================================================================
  38. // 
  39. // ============================================================================
  41. int     main(void)
  42. {
  43. auto int number;
  44.     // test the constructors
  45.     auto    CName       nameOne("Grace", "Slick");
  46.     const   CName       nameTwo = nameOne;
  47.     auto    CName       nameThree;
  49.     // display the contents of each newly-constructed object...
  51.     cout << "nameOne = ";
  52.     cout << nameOne;
  53.     cout << "nameTwo = ";
  54.     cout << nameTwo;
  55.     cout << "nameThree = ";
  56.     cout << nameThree;
  60.     // should see "Grace Slick"
  61.     cout << "nameOne = ";
  62.     nameOne.WriteFullName();
  63.     cout << endl;
  65.     // should see "Grace Slick" again
  66.     cout << "nameTwo = ";
  67.             nameTwo.WriteFullName();
  68.     cout << endl;
  70.     // should see nothing
  71.     cout << "nameThree = ";
  72.             nameThree.WriteFullName();
  73.     cout << endl;
  75.     // try the "read" function
  76.     cout << "Enter your first and last names separated by a space: ";
  77.     nameThree.ReadFullName();
  78.     cout << "Your name is: " << nameThree << endl << endl;
  80.    // try the assignment operator
  81.     nameOne = nameThree = nameTwo;
  82.     cout << "Testing the assignment operator..." << endl;
  83.     cout << "nameOne == " << nameOne << endl;
  84.     cout << "nameTwo == " << nameTwo << endl;
  85.     cout << "nameThree == " << nameThree << endl << endl;
  86. cin >> number;
  87.     // open the name data file
  88.     auto    ifstream        nameFile("names.dat");
  89.     if (nameFile.fail())
  90.         {
  91.         cerr << "Error opening the input file..." << endl;
  92.         exit(EXIT_FAILURE);
  93.         }
  95.     // use the object to display the contents of the name data file
  96.     cout << "Here are the contents of the name file: " << endl;
  97.     while (nameFile >> nameThree)
  98.         {
  99.         cout << nameThree << endl;
  100.         }
  101. cin >> number;
  102.     // close the file stream and return
  103.     nameFile.close();
  104.     return (EXIT_SUCCESS);
  106.     return 0;
  107. }  // end of "main"
Aug 28 '07 #4
5 New Member
This was my Homework as you can see, i have the program running all except the fact that our professor made the class const CName; so that means further down when I try to use the nameThree.Write FullName(); I get the error message??

This was my question??

so mutable you say hey??

thanks if anyones else has input that would be great?? Time is ticking until 6pm today,
thank you
thank you
thank you
while( !AnsweredQ)
cout<< "Help";
Aug 28 '07 #5
9,065 Recognized Expert Moderator Expert
so mutable you say hey??
I doubt making the data mutable is what your professor wants.

mutable data is really data that does not effect the "state" of the object, that is data that is used in a temporary fashion.

By the sounds of it you need to make the methods const.
Aug 28 '07 #6
5 New Member
Thank you for your help i found the solution

next time

i just need to make my member function a const didn't know that

thank you Bafa!
Aug 29 '07 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Old Wolf | last post by:
I tried this code: #include <iostream> #include <string> template<typename T> struct enum_properties { static const long max; static const std::string name;
by: kelvSYC | last post by:
This little bit of seeminly innocent code seems to give me these two errors, all on the line that declares check(). Is there some part of C++ that I'm missing out on? class Condition { public: Condition() {} virtual ~Condition() {} virtual bool check() const;
by: Irish | last post by:
Hello all :) Hopefully someone can shed some light on this problem I'm having. I'm trying to declare a variable to a type of class I've defined (which is a minHeap), but actually instantiate it later when I get a command from the user. This is my class and if you look down a lil you can see what I'm trying to do in my main(). I want to ask for the size from the user, but when I try to I can't get my code to compile. Here is the class...
by: classicist | last post by:
Suppose I have a function which takes an argv-style pseudo-matrix and modifies neither the strings nor the pointers. How do I use the const qualifier to signal my intentions w/o drawing compiler warnings? E.g., int sum_of_lengths_of_strings( const char **s, int ns ) { int i, len = 0; for ( i = 0; i < ns; ++i )
by: John Salerno | last post by:
Here's my full code: using System; using System.Collections.Generic; using System.Text; using System.IO; namespace PatternMatcher { class Program
by: N. Demos | last post by:
I have a user control with code behind of which two instances are created/declared in my aspx page. The aspx page has code behind also, as I need to access methods of the usercontrols on page submit. I've read several post here and articles on the web on this topic. What little I have learned from them is that you have to pre-compile the usercontrol in order to access it in the aspx code behind. I did this, compiling the usercontrol...
by: mark.moore | last post by:
I know this has been asked before, but I just can't find the answer in the sea of hits... How do you forward declare a class that is *not* paramaterized, but is based on a template class? Here's what I thought should work, but apparently doesn't: class Foo; void f1(Foo* p)
by: vishwesha.guttal | last post by:
Hi, I am having troble declaring a const array. If the array size is small, then one can do as follows: const double array = {1, 2, 3, 4, 5}; What if I have an array of size say 1000 or 10000 which, lets say, I am reading from a data file? Then manually entering the values is impossible. So how do I declare such a constant array?
by: jdurancomas | last post by:
Dear all, I'm trying to declare the operator++ to a nested class. The nested class is not template but the container it is. The code used in teh sample program is included bellow: #include <iostream>
by: Tammy | last post by:
Hello all, I am wondering what is the best way to declare a struct to be used in other c and c++ files. Such as for a C API that will be used by others. 1. Declaring the typedef and the struct in the header file and including this file in all source files that need it? For example: mystruct.h
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.