0

The code below is showing syntax error in visual studio. Please help me figure out the error😅😅

// Header File #ifndef MYCLASS_H #define MYCLASS_H class Myclass { public: Myclass(string a, string b); private: string var1; const string var2; }; #endif // Source File #include "Myclass.h" #include <iostream> using namespace std; Myclass::Myclass(string a, string b) : var1 (a), var2 (b) { cout << var1 << endl; cout << var2 << endl; } int main(){ MyClass obj("Hello", "World"); } // THE END

11th Apr 2020, 11:51 AM
Santosh Pattnaik
Santosh Pattnaik - avatar
5 Réponses
- 1
Thanks Andriy. But there was another error that is now figured out. The line "using namespace std;" should be written under the string header declaration in the header file. Rather, thanks🙂🙂
11th Apr 2020, 12:47 PM
Santosh Pattnaik
Santosh Pattnaik - avatar
+ 3
You didn't include string header to use string class. Header file should be like this: #ifndef MYCLASS_H #define MYCLASS_H #include <string> class Myclass { public: Myclass(std::string a, std::string b); private: std::string var1; const std::string var2; }; #endif also you have spelling error inside main function. It should be: Myclass obj("Hello", "World"); (not MyClass)
11th Apr 2020, 12:02 PM
andriy kan
andriy kan - avatar
+ 2
don't write line using namespace std; in header files. This is bad programming style! (You get some problems when you will use other namespaces in C++ file which includes your header with using namespace std) Use it only inside C++ file. In header file use namespace prefix instead. (std::) I wrote code with namespace prefixes. May be you forgot to insert std:: prefix before some strings?
11th Apr 2020, 12:58 PM
andriy kan
andriy kan - avatar
+ 2
@BILAL AHMAD BHAT This is not an error. var2 is member of the class. It is initialized in the constructor. It is allowed.
11th Apr 2020, 1:05 PM
andriy kan
andriy kan - avatar
0
string var2 is const.. so it needs to be initialized at the time of declaration.. you can't keep a const variable uninitialized, it can't be initialized later.
11th Apr 2020, 12:56 PM
BILAL AHMAD BHAT