Can someone help me to make code

–2 votes
asked Nov 16 by Amina Slabic (110 points)
I did a lot of work and its easy program, but idk how to put more than 2 methds in one class, c++. If i tried something from internet it just doesnt want to work. so if someone can help me ty

1 Answer

+1 vote
answered Nov 18 by Peter Minarik (12,220 points)
edited Nov 18 by Peter Minarik

Share your code

Please, share your code so we can see what you did and find out what the mistake was there. This way you can get personalised answer to your question.

Examples

I can provide some silly examples, maybe they help too.

Simple class:

#include <iostream>

class Dog
{
public:
    void Bark()
    {
        std::cout << "Woof, woof" << std::endl;
    }
    
    void Eat()
    {
        std::cout << "Yum, yum" << std::endl;
    }
};

int main()
{
    Dog dog;
    dog.Bark();
    dog.Eat();

    return 0;
}

Class separated to header and source file:

You can download the sample project from here. Please note that functions marked as const can not change the state of the class (right now the only "state" is the _name). If you want to change the class itself in the method, do not mark those method as const.

dog.h

#pragma once

#include <string>

class Dog
{
private:
    std::string _name;

public:
    Dog(std::string name);
    void Bark() const;
    void Eat(const std::string & food) const;
};

dog.cpp

#include "Dog.h"

#include <iostream>

Dog::Dog(std::string name) : _name(name) { }

void Dog::Bark() const
{
    std::cout << _name << " barks: Woof-woof" << std::endl;
}

void Dog::Eat(const std::string & food) const
{
    std::cout << _name << " eats " << food << ": Yum-yum" << std::endl;
}

main.cpp

#include "Dog.h"

int main()
{
    Dog dog("Butch");
    dog.Bark();
    dog.Eat("steak");

    return 0;
}

Sample execution:

Butch barks: Woof-woof
Butch eats steak: Yum-yum
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...