I have a header and cpp file.I'm trying to learn OOP so I did a small program that handles classes.In the header I have declared the class and in the main file I'm implementing the methods.

m_prvi = first number
m_drugi = second number
m_rezultat = result

So I call newobject.Summate(5,3) and then newobject.print() and it does everything fine but why is not the constructor working properly?

It's a default constructor which should intiliaze the attributes (set their values to zero) but it doesn't.Why not?

EADER FILE

#ifndef _CLASS_H
#define _CLASS_H

class COseba
{
private:
	int m_prvi;
	int m_drugi;
	int m_rezultat;
public:
	void setNumber(int a, int b);
	void Sestej();
	void Izpisi();

	COseba();
//	~COseba();
};

#endif

MAIN FILE

#include <iostream.h>
#include "class.h"

void COseba::setNumber(int a, int b)
{
	m_prvi = a;
	m_drugi = b;
}

void COseba::Sestej()
{
	m_rezultat = m_prvi + m_drugi;
}

void COseba::Izpisi()
{
	cout << "Rezultat je: " << m_rezultat << endl;
}

COseba::COseba()
{
	m_prvi = 0;
	m_drugi = 0;
	m_rezultat = 0;
}

int main()
{
	COseba novi;

	novi.setNumber(5,3);
	novi.Sestej();
	novi.Izpisi();

	COseba();//::COseba();

	novi.Izpisi();

	return 0;
}

Recommended Answers

All 4 Replies

int main()
{
	COseba novi;

	novi.setNumber(5,3);
	novi.Sestej();
	novi.Izpisi();

	COseba();//::COseba();

	novi.Izpisi();

	return 0;
}

a lone call to the constructor won't do anything useful - a constructor call means a new object is created (and in the case above, the object is created, does nothing, then destroyed)

change that line to

novi = COseba();

This calls the constructor to create a new COseba object, and copies the new object to novi

Ofcourse! Thank you Bench!

It may be your compiler, you should try putting the class constructor and other members in the same file as the class declaration.

Personally I declare the member functions in the class {} structure it's self, not after the class declaration, less typing.

I moved declarations to another .cpp file because I want it to be more "reviewable".I'm just starting with OOP with C++ so inline declarations could easily confuse me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.