that guy
that guy

Reputation: 404

c++ constructor not working

This is my makeAccount.cpp:

#include "account.h"
#include <string>
using namespace std;

int makeAccount::getAccountNumber()
{
    return accountNumber;
}

double makeAccount::getAccountSaldo()
{
    return accountSaldo;
}

string makeAccount::getName()
{
    return name;
}

makeAccount::makeAccount(std::string naam, int id, double saldo)
{
    naam = name;
    id = accountNumber;
    saldo = accountSaldo;
}

this is my makeAccount.h

#include <string>
#include <sstream>

class makeAccount
{
public:
    makeAccount(std::string naam, int id, double saldo);
    int getAccountNumber();
    double getAccountSaldo();
    std::string getName();
private:
    int accountNumber;
    double accountSaldo;
    std::string name;
};

this is my main.cpp

#include "account.h"
#include <iostream>
using namespace std;

int main()
{
    makeAccount::makeAccount test("test", 30,  23.5);
    cout << test.getName() << endl;
    cout << test.getAccountNumber() << endl;
    cout << test.getAccountSaldo() << endl;
    return 0;
}

Now I have the following problem, when I try to execute this code I get this: 1606416736 6.95322e-310 I think there is a problem in my account.h where I declare the constructor but I can't figure out what exactly is the problem. However when I do something like this:

private:
    int accountNumber = 1234;
    double accountSaldo = 1;
    std::string name = "test";
};

It does work, so I think i either way have something wrong in my constructor or where in my makeAccount.cpp where I have this code:

makeAccount::makeAccount(std::string naam, int id, double saldo)
{
    naam = name;
    id = accountNumber;
    saldo = accountSaldo;
}

Thanks in advance.

Upvotes: 3

Views: 7746

Answers (2)

nos
nos

Reputation: 229058

You have your assignments reversed.

You'll want this:

makeAccount::makeAccount(std::string naam, int id, double saldo)
{
    name = naam;
    accountNumber = id;
    accountSaldo = saldo;
}

Normally you'd want to use an initialization list, your constructor should look like this:

makeAccount::makeAccount(std::string naam, int id, double saldo) :
  accountNumber(id),
  accountSaldo(saldo),
  name(naam)
{}

Upvotes: 8

OiRc
OiRc

Reputation: 1622

change this

makeAccount::makeAccount(std::string naam, int id, double saldo)
{ 
naam = name;
id = accountNumber;
saldo = accountSaldo;
}

with:

makeAccount::makeAccount(std::string naam, int id, double saldo)
{
name = naam;
accountNumber = id;
accountSaldo = saldo;
}

now should works

Upvotes: 1

Related Questions