compiler not recognizing methods defined outside the class declaration - c++

new to c++.Im stuck with a question here, i made a bank account program which has functions like withdraw() and deposit() defined in a class called 'account'.So, i defined my class in a different file(account.h) also i defined withdraw() inside the class itself but defined the deposit() function outside the class in 'account.cpp' file.When i compile it i get the following error -
undefined reference to 'account::deposit(int)'
I'm not an expert but i think it doesn't recognize that i defined the define() function int account.cpp.Also i use vscode (idk if that helps).
here is the code-
main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "account.h"
int main()
{
account Ajay_bank;
if (Ajay_bank.withdraw(1000))
{
std::cout << "withdraw successful\n";
}
else
{
std::cout << "withdraw failed";
}
if (Ajay_bank.deposit(2000))
std::cout << "Deposit successful";
else
std::cout << "[error - NET404]:try again later";
}
account.cpp-
#include "account.h"
bool account::deposit (int amount)
{
balance += amount;
return true;
}
account.h-
#ifndef _ACCOUNT_H
#define _ACCOUNT_H
#include <string>
class account
{
private:
std::string name;
int balance {200};
int credit_score {};
public:
bool withdraw (int amount)
{
if (balance - amount >= 0)
{
balance -= amount;
return true;
}
else
return false;
}
bool deposit (int amount);
};
#endif
Thanks.

While compiling more than source file (.cpp) you should compile with that files.
g++ main.cpp account.cpp -o main
then run it like:
./main
If you try with that command you can run successfully

Related

Array of objects prints blank string

(The issue has been solved and the solution has been added as comment line to main.cpp)
The problem I'm having is described in the main.cpp file. I already checked another questions about this and none of them really helped.
I'm trying to create a console application with C++ where you can add BOOKS to the LIBRARY. In the library class, there is a displayInfo() function which displays the info of a particular book. It can display integer or double valued informations without having a problem however it is having a trouble when I try to display string typed informations. It just prints blank. Let me give you a little sample of my code.
Here is Book.h
#ifndef BOOK_H
#define BOOK_H
#include <string>
class Book
{
friend class Library;
public:
void setName();
std::string getName();
private:
std::string nameOfBook;
};
#endif
Book.cpp
#include "Book.h"
#include <iostream>
#include <string>
using namespace std;
void Book::setName()
{
string nameOfBook;
cout << "Please enter the name of the book: ";
cin >> nameOfBook;
this->nameOfBook = nameOfBook;
}
string Book::getName()
{
return nameOfBook;
}
Library.h
#ifndef LIBRARY_H
#define LIBRARY_H
#include "Book.h"
#include <array>
class Library
{
private:
std::array <Book , 10> bookArray; // I have to use this
public:
void addBook();
void displayInfo();
};
#endif
Library.cpp
#include "Library.h"
#include "Book.h"
#include <iostream>
#include <string>
#include <array>
using namespace std;
void Library::addBook()
{
bookArray[0].setName();
}
void Library::displayInfo()
{
cout << "The book: " << bookArray[0].getName() << endl;
}
And main.cpp
#include <iostream>
#include "Book.h"
#include "Library.h"
#include <string>
#include <array>
using namespace std;
int main()
{
// The problem is solved
// Create the objects out of the loop
// Library obj1 <---- this solved it
while (true)
{
int number; // Ask user what to do
cout << "Press 1 to add a book\n"
<< "Press 2 to display info\n"
<< "Press 0 to quit\n";
cin >> number;
if (number == 1) // Add a book
{
Library obj1; // <------ THIS IS WRONG
obj1.addBook(); // Consider we named the book as 'Fly'
}
else if (number == 2)
{
Library obj1; // <------ THIS IS WRONG
obj1.displayInfo(); // ******* The output I'm expecting is The Book: Fly
// But instead, it only gives me The Book:
// I have 4 more strings like this in the main project and all of them have the same problem
}
else if (number == 0) // Everything else
{
break;
}
else
{
cout << "Wrong input\n";
continue;
}
}
}
Edit:
I coded this with VS Code and compiled it with MinGW (8.2.0) if it matters.
one problem in your code is that you have many instances of a library class so addBook is landing in one object and displayInfo in a new one (empty one)
you have to:
int main()
{
Library obj1; // declare the lib in scope for all the cases
while (true)
{
int number; // Ask user what to do
cout << "Press 1 to add a book\n"
<< "Press 2 to display info\n"
<< "Press 0 to quit\n";
cin >> number;
if (number == 1) // Add a book
{
obj1.addBook(); // Consider we named the book as 'Fly'
}
else if (number == 2)
{
//Library obj1;
obj1.displayInfo(); // ******* The output I'm expecting is The Book: Fly
// But instead, it only gives me The Book:
// I have 4 more strings like this in the main project and all of them have the same problem
}
else if (number == 0) // Everything else
{
break;
}
else
{
cout << "Wrong input\n";
continue;
}
}
}
u are creating the object again in every iteration of the loop. therefore overwriting the old object that has been given a name.

Splitting up classes c++

I'm facing a problem for the past couple of days.
First of all, I had a project that I've done. But now I've to split it's classes.
Here's how I split the classes (a class as an example):
Header file:
#ifndef QUESTION_H
#define QUESTION_H
#include <string>
#include <iostream>
#include <fstream>
#include "Answer.h"
using namespace std;
// Name -- hold a first and last name
class Question {
protected:
string type; // Type of the question, e.g MC or TF
string text; // Text of the question
public:
// Default constructor
Question ();
// Getters and setters
string getType();
string getText();
void setType (string t);
void setText (string t);
// displayText -- Display the text of the question, unformatted at present
void displayText();
// Template pattern -- algorithm in parent which does its work calling child methods
virtual void displayAnswers();
virtual void display ();
// Virtual pure functions that must be implemented by each derived class
virtual int grade (Answer*); // grade a given answer
virtual Answer* readAnswer(istream &); // read a user's answer
};
#endif
Alright, now here is the implementation:
#include "Question.h"
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
Question::Question () { type = ""; text = ""; }
// Getters and setters
string Question::getType() { return type; }
string Question::getText() { return text; }
void Question::setType (string t) { type = t; }
void Question::setText (string t) { text = t; }
// displayText -- Display the text of the question, unformatted at present
void Question::displayText() {
cout << text;
}
// Template pattern -- algorithm in parent which does its work calling child methods
void Question::displayAnswers(){ }// Require derived classes to implement
void Question::display () {
Question::displayText();
Question::displayAnswers(); // Call derived class's displayAnswers
}
// Virtual pure functions that must be implemented by each derived class
int Question::grade (Answer*){ return 0; } // grade a given answer
Answer* Question::readAnswer(istream &){ return 0; } // read a user's answer
Ok, so I've done the other classes the same exact way.
Now what's left is the MakeFile, here it is:
project: Question MCQuestion TFQuestion Answer IntAnswer CharAnswer Main
g++ -std=c++11 Question MCQuestion TFQuestion Answer IntAnswer CharAnswer Main -o project
.cc.o:
g++ -std=c++11 -c <−o#
Now when I try running make it brings up this message:
g++ Question.cpp -o Question
/usr/lib/gcc/i586-suse-linux/4.7/../../../crt1.o: In function `_start':
/home/abuild/rpmbuild/BUILD/glibc-2.17/csu/../sysdeps/i386/start.S:113: undefined reference to `main'
collect2: error: ld returned 1 exit status
make: *** [Question] Error 1
Can somebody explains it? or what am I doing wrong?
Thanks.
Edited:
Main.cc :
#include <iostream>
#include <fstream>
#include <string>
#include "Question.h"
#include "MCQuestion.h"
#include "TFQuestion.h"
#include "Answer.h"
#include "IntAnswer.h"
#include "CharAnswer.h"
#include <vector>
using namespace std;
int main () {
vector<Question *> questions; // Holds pointers to all the questions
ifstream infile ("questions.txt"); // Open the input file
int totalCorrect = 0; // Initialize the count from number of correct answers
// Read each question and place it into the questions vector
string questionType;
while ( getline (infile, questionType) ) {
if (questionType == "MC") {
MCQuestion *mc = new MCQuestion();
mc->read(infile);
questions.push_back(mc);
}
else if ( questionType[0] == 'T' or questionType[0] == 'F' ) {
TFQuestion* tf = new TFQuestion();
tf->read(infile);
tf->setAnswer(questionType[0]);
questions.push_back(tf);
}
else {
cout << "Input file is corrupt. Expected to find MC, T or F; found \"" << questionType << "\" instead." << endl;
}
}
infile.close();
// Pose each question, read and grade answers, tally total
int questionNo = 0;
for (auto &question: questions) {
// Pose the question
questionNo++; cout << questionNo << ". ";
question->display();
// Get the user's answer
Answer* ans = question->readAnswer(cin);
// Grade it and increment total
int correct = question->grade(ans);
totalCorrect = totalCorrect + correct
// Inform the user as to whether or not they got the question correct
cout << "Your answer was " << (correct?"":"not ") << "correct\n" << endl;
}
// Print the overall score
cout << "Your overall score is " << totalCorrect << "/"
<< questions.size() << endl;
return 0;
}
You create Makefile with lot of mistakes:
Should be something like this:
project: Question.o
g++ -std=c++11 $^ -o $#
.cc.o:
g++ -std=c++11 -c $< -o $#
add other dependencies into project in similar way, not forget defining main function in some of your .cc files.

Undefined symbols for architecture x86_64 c++ class

In an attempt to code a basic 'Bank Account' class separated into a header file, and two .cpp files the following error messages are displayed when attempting to compile.
(Developing in vim through the terminal (OS X Yosemite 10.10.5))
I am not sure what the error messages are referring to nor how to solve the issue. Thanks in advance for any insight and feedback.
Terminal Command & Error Messages:
$ g++ -std=c++11 -Wall Account.cpp
$ g++ -std=c++11 -Wall test.cpp
Account.h
//Account.h
//Account class definition. This file presents Account's public
//interface without revealing the implementation of Account's member
//functions, which are defined in Account.cpp.
#ifndef ACCOUNT_H
#define ACCOUNT_H
#include <iostream>
class Account
{
public:
Account(int amount); //constructor initialize accountBalance
void credit(int creditValue); //credits the account balance
void debit(int debitValue) ; //debits the account balance
int getBalance() const; //gets the account balance
private:
int accountBalance;//account balance for this Account
};//end class Account
#endif
Account.cpp
//Account.cpp
//Account member function definitions. This file contains
//implementations of the member functions prototype in Account.h
#include <iostream>
#include "Account.h" //include definition of class Account
using namespace std;
//constructor initializes accountBalance with int supplied
//as argument
Account::Account(int amount)
{
if(amount >= 0)
{
accountBalance = amount;
}
else
{
accountBalance = 0;
cerr << "The initial balance was invalid" << endl;
}
}
//function to credit amount to account balance
//value must be greater than zero
void Account::credit(int creditValue)
{
if(creditValue > 0)
{
accountBalance += creditValue;
}
else
{
cout << "Credit value cannot be negative nor zero.\n";
}
}
//function to debit amount from account balance
//value cannot exceed current account balance
void Account::debit(int debitValue)
{
if(accountBalance >= debitValue)
{
accountBalance -= debitValue;
}
else
{
cout << "Debit amount exceeds account balance.\n";
}
}
//function to get the account balance
int Account::getBalance() const
{
return accountBalance;
}
test.cpp
#include <iostream>
using namespace std;
// include definition of class Account from Account.h
#include "Account.h"
// function main begins program execution
int main()
{
Account account1( 50 ); // create Account object
Account account2( 25 ); // create Account object
Account account3( -25 ); // attempt to initialize to negative amount;
// display initial balance of each object
cout << "account1 balance: $" << account1.getBalance() << endl;
cout << "account2 balance: $" << account2.getBalance() << endl;
int depositAmount; // stores deposit amount read from user
cout << "\nEnter deposit amount for account1: "; // prompt
cin >> depositAmount; // obtain user input
cout << "\ndeposit " << depositAmount
<< " into account1 balance\n\n";
account1.credit( depositAmount ); // add to account
return 0; // indicate successful termination
} // end main
The problem is that you're compiling each .cpp file as if it were the only file in the program. Instead, you must use the -c option to your C++ compiler (assuming GCC or Clang) to compile each .cpp file. This will give you a corresponding set of .o (object) files. You then link these together with a final command line like this:
g++ -o myprogname Account.o test.o
If you use a build tool like CMake, these details will be handled automatically.

C++ Error: No Member in Class?

I'm working on C++, and this is just a very basic program, but I'm still getting an error.
The error message is:
'class secondary' has no member named 'getting'.
Why is this? It works for my void setting, but not for getting? What am I doing wrong here?
main.cpp
#include <iostream>
#include <string>
#include "secondary.h"
using namespace std;
int main(){
secondary s;
int scale;
cout << "On a scale of 1-10, how awesome are you?" << endl;
cin >> scale;
cout << endl;
s.setting(scale);
cout << s.getting();
return 0;
}
secondary.h
#ifndef SECONDARY_H
#define SECONDARY_H
#include <string>
class secondary
{
public:
void setting(int x);
string getting();
};
#endif // SECONDARY_H
secondary.cpp
#include "secondary.h"
#include <iostream>
#include <string>
using namespace std;
void secondary::setting(int x){
factor = x;
}
string secondary::getting(){
string result;
if(factor < 3){
result = "You have a very low self esteem.";
}elseif(factor > 3){
if(factor > 7){
result = "You have a very high self esteem."
}else{
result = "You have a medium self esteem."
}
}
return result;
}
private factor;
Actually, looking at this again, and deeper, this code has many issues (semicolons missing at key points and the private int definition should have been in the header file, not the cpp file 9t(private is its own section, see below):The problem, from what I can see, s has not yet been instantiated yet, do so and the operation should work correctly.
Please also note that when factor was defined in the cpp file, it was defined at bottom, it should actually be defined before any use of the variable to be defined (in the header file is better meet with common/conventional coding standards).
Please check this tested code:
main.cpp
#include <iostream>
#include <string>
#include "secondary.h"
using namespace std;
int main(){
secondary s;
int scale;
cout << "On a scale of 1-10, how awesome are you?" << endl;
cin >> scale;
cout << endl;
s.setting(scale);
cout << s.getting();
return 0;
}
secondary.h
#ifndef SECONDARY_H
#define SECONDARY_H
#include <string>
class secondary
{
public:
void setting(int x);
std::string getting();
private: // Note: this is how you do private
int factor; // This is the definition with type int, missing in original
};
#endif // SECONDARY_H
secondary.cpp
#include "secondary.h"
#include <iostream>
#include <string>
using namespace std;
void secondary::setting(int x){
factor = x;
}
string secondary::getting(){
string result;
if (factor < 3){
result = "You have a very low self esteem.";
}else if(factor > 3){
if (factor > 7){
result = "You have a very high self esteem.";
}
else{
result = "You have a medium self esteem.";
}
}
return result;
}

Double declaration c++

So I have some code in couple of files:
cells.cpp:
#include "cells.h"
#include <iostream>
using namespace std;
char convertIntChar (int symbolNumber)
{
char charR;
switch (symbolNumber)
{
case 0:
charR='0';
break;
// lust of case code here
case 63:
charR='\\';
break;
}
return charR;
}
class cell
{
public:
int iPosition;
char chPosition;
cell ()
{
static int i = -1;
i++;
chPosition=convertIntChar (i);
iPosition=i;
cout << " " << iPosition; //two lines of code to test
cout << " " << chPosition; //constructor
}
protected:
};
main.cpp
#include <iostream>
#include "cells.h"
#include "pointer.h"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
createPointer();
cell cells[64];
return 0;
}
And comeplytly a cells.h
#ifndef CELLS_H_INCLUDED
#define CELLS_H_INCLUDED
#pragma once
class cell
char convertIntChar(int symbolNumber);
#endif // CELLS_H_INCLUDED
There I have an erros that sounds like
//filepath\|5|error: two or more data types in declaration of 'convertIntChar'|
||=== Build finished: 1 errors, 0 warnings (0 minutes, 7 seconds) ===|
What can it be. Sorry for noob question anyway.
First, this forward declaration needs a semi-colon:
class cell;
// ^
Second, you cannot use a forward declaration here. main.cpp needs to see the cell class definition. So you should put the definition in cells.h. For example:
cells.h:
#ifndef CELLS_H_INCLUDED
#define CELLS_H_INCLUDED
class cell
{
public:
int iPosition;
char chPosition;
cell ();
};
char convertIntChar(int symbolNumber);
#endif
cells.cpp:
#include "cells.h"
#include <iostream>
char convertIntChar (int symbolNumber)
{
char charR;
// as before
return charR;
}
cell::cell ()
{
static int i = -1;
i++;
chPosition=convertIntChar (i);
iPosition=i;
std::cout << " " << iPosition; //two lines of code to test
std::cout << " " << chPosition; //constructor
}
You have class cell in the cpp file which should go into the .h file.
Then in cells.h you are missing a ; after class cell.
Insterad of the forward declaration in cell.h, put the class there.