-1

While trying to pass a value to a constructed, I kept getting errors about that the constructed can't accept the value, is that because of the main class ? :

#include <iostream>
#include <string>
using std::cout;
using std::endl;

Class GettingVal{
    public:
        GettingVal(string z){
            setName(z);
        }
        void setName(string x){
            name = x;
        }
        string getName(){
            return name;
        }
    private:
        string name;
}  
using namespace std;
int main()
{
  GettingVal Name("Hiiiiiii");
  std::cout << Name.getName();
}

Here is the error I get after compiling the project :

error: ‘Name’ was not declared in this scope
   std::cout << Name.getName();
  • 2
    I get a lot more errors than that, there's a lot of typos and use before declaration errors here: https://godbolt.org/z/8znqec – UnholySheep Jan 05 '21 at 21:25
  • 2
    This code doesn't compile for multiple reasons. `Class` instead of `class`, no `;` after class definition, `string` before the `using namespace std` statement, etc. – 0x5453 Jan 05 '21 at 21:25
  • 1
    Please check you are copy pasting the actual code you are compiling – M.M Jan 05 '21 at 21:27
  • 2
    When you have many many errors fix the very very first error and recompile. If you want help here you need to give us one specific error to deal with - this is a bit too general. – Andy Newman Jan 05 '21 at 21:30
  • If this is Visual Studio I recommend you look at the error messages in the Output tab and not the errors list for 2 reasons. 1. The errors in the Output Tab are always in proper order, 2. The error messages in the Output Tab are often in a more verbose format which sometimes helps. #1 is important because many times a single error could cause multiple problems. – drescherjm Jan 05 '21 at 21:47

1 Answers1

4

For starters there is a typo. There is a missed semicolon

Class GettingVal{
   //...
};
^^^

The standard class std::string is declared in the namespace std. So you have to use either the qualified name std::string in the class definition or to use the using declaration

using std::string;

before the class definition.

And remove the redundant using directive

using namespace std;

The member functions of the class could be declared and defined the following way

    GettingVal( const std::string &z){
        setName(z);
    }
    void setName( const std::string &x){
        name = x;
    }
    const std::string & getName() const {
        return name;
    }

Though the constructor could be defined simpler

    GettingVal( const std::string &z) : name( z ){
    }
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335