LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 08-20-2012, 09:22 AM   #1
mreff555
Member
 
Registered: Sep 2011
Location: Philly
Distribution: Gentoo
Posts: 473

Rep: Reputation: Disabled
Basic C++ OOP - Constructors


I have a dumb question about constructors. As I was beginning to ask another question I think I just figured out what I did wrong.

If I have a constructor with arguments, is the constructor called when I create the object, or when I pass arguments to it? for example, I have a class called PixelCount which has an argument in the constructor.

Code:
PixelCount x;    //here?
x(argv[1]);      //or here?
 
Old 08-20-2012, 09:40 AM   #2
johnsfine
LQ Guru
 
Registered: Dec 2007
Distribution: Centos
Posts: 5,286

Rep: Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197
Quote:
Originally Posted by mreff555 View Post
If I have a constructor with arguments, is the constructor called when I create the object, or when I pass arguments to it?
Those should not be two separate statements. Have you tried compiling your code? Without seeing more code, I can't be sure, but I suspect your error should be caught at compile time, rather than do the wrong thing at run time.

Quote:
Code:
PixelCount x;    //here?
x(argv[1]);      //or here?
The default constructor is called by the first of those lines. If there is no default constructor, that is a compile time error.

The second line does not call any constructor nor pass an argument to one. It calls the object's operator() function and is a compile time error if that is not defined.

I think the code you intended is:
Code:
PixelCount x(argv[1]);

Last edited by johnsfine; 08-20-2012 at 09:41 AM.
 
Old 08-20-2012, 10:13 AM   #3
mreff555
Member
 
Registered: Sep 2011
Location: Philly
Distribution: Gentoo
Posts: 473

Original Poster
Rep: Reputation: Disabled
Alright here is my problem. I am new to Programming and C++, very new to classes and object oriented programming. Here is the include and source for a small class I'm working on.

Code:
#include <opencv/cv.h>
#include <opencv/highgui.h>
#ifndef PIXELCOUNT_H
#define PIXELCOUNT_H
class PixelCount
{
    unsigned long white,black;
    public:
    IplImage* img;
    PixelCount(char*);
    void init(unsigned long, unsigned long);
    unsigned long getArea();
    unsigned long getWhite();
    unsigned long getBlack();

    virtual ~PixelCount();
    protected:
    private:
};

#endif // PIXELCOUNT_H
Code:
#include "include/PixelCount.h"
PixelCount::PixelCount(char* infile):
img(cvLoadImage(infile,0))
{

}
unsigned long getArea() {return (img)->width* (img)->height;}
unsigned long getWhite() {return cvCountNonZero(img);}
unsigned long getBlack() {return getArea()-getWhite();}

PixelCount::~PixelCount(){
    cvReleaseImage(&img);
    }
what I want to be able to do is to create an object from an argument and then have the function implicitly refer to the image so I don't have to give them arguments again. I have tried everything and I can't get it to work. Here is an example of what I want to be able to do:

Code:
PixelCount x(argv[1]);
std::cout << "Number of black pixels:" << x.getBlack() <<endl;
what am I doing wrong?
 
Old 08-20-2012, 10:51 AM   #4
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Kubuntu, Fedora, RHEL
Posts: 1,541

Rep: Reputation: 335Reputation: 335Reputation: 335Reputation: 335
Quote:
Originally Posted by mreff555 View Post
what am I doing wrong?
You have not fully indicated what is it that you did, and what results you are seeing. I do not know OpenCV at all, however with 5 minutes of Googling to see examples of the API, and a little creative guessing to install the relevant libraries on my system, I got a program that is very similar to yours to function "properly".

Here it is:
Code:
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <cassert>
#include <iostream>

class PixelCount
{
public:
    PixelCount(const char* imageFilename)
        : img(cvLoadImage(imageFilename, 0))
    {
        assert(img != NULL);
    }

    virtual ~PixelCount()
    {
        cvReleaseImage(&img);
    }

    unsigned long getArea() const  { return img->width * img->height; }
    unsigned long getWhite() const { return cvCountNonZero(img); }
    unsigned long getBlack() const { return getArea()-getWhite(); }

private:
    IplImage* img;
};

int main(int argc, char** argv)
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " <image>" << std::endl;
        return -1;
    } 

    PixelCount pc(argv[1]);

    std::cout << "area : " << pc.getArea()  << std::endl;
    std::cout << "white: " << pc.getWhite() << std::endl;
    std::cout << "black: " << pc.getBlack() << std::endl;
}
To build the code:
Code:
g++ `pkg-config opencv --cflags` PixelCount.cpp `pkg-config opencv --libs`
To run it:
Code:
./a.out image.jpg
 
1 members found this post helpful.
Old 08-20-2012, 02:48 PM   #5
mreff555
Member
 
Registered: Sep 2011
Location: Philly
Distribution: Gentoo
Posts: 473

Original Poster
Rep: Reputation: Disabled
Quote:
You have not fully indicated what is it that you did, and what results you are seeing.
If that's the case you did an excellent job extrapolating!

Quote:
I do not know OpenCV at all, however with 5 minutes of Googling to see examples of the API, and a little creative guessing to install the relevant libraries on my system, I got a program that is very similar to yours to function "properly".
Congratulations. I guess that's why you are considered a "senior member." Pardon me if I came off as someone who toils on a problem for five minutes and posts, wasting everyone's precious time. I just spent Thursday, Friday, the better part of the weekend, and half of today working on it. Thanks for making me feel retarded.

My original code, which did worked looked quite similar to yours. The problems arose when I attempted to separate the class/include.
It turns out that the problem was that I was not preceeding function names with "<classname>::" in the source files. Something I didn't have to do in the past when it was all in one file.

Anyway, I appreciate you help. Just not the attitude. It's easy to look up information if you already know what you are doing? and not everyone who posts is just looking for quick answers.
 
Old 08-20-2012, 05:15 PM   #6
NevemTeve
Senior Member
 
Registered: Oct 2011
Location: Budapest
Distribution: Debian/GNU/Linux, AIX
Posts: 4,852
Blog Entries: 1

Rep: Reputation: 1868Reputation: 1868Reputation: 1868Reputation: 1868Reputation: 1868Reputation: 1868Reputation: 1868Reputation: 1868Reputation: 1868Reputation: 1868Reputation: 1868
> > You have not fully indicated what is it that you did, and what results you are seeing.
> If that's the case you did an excellent job extrapolating!

Yes he did, but next time you're asking for help don't rely on that: quote the actual error-message you got from the compiler/linker instead, and paste the relevant pieces of source.
 
Old 08-20-2012, 07:26 PM   #7
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,610
Blog Entries: 4

Rep: Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905
Keep this in mind: a "constructor" is just an initialization subroutine. That's it, that's all.

When C++ is told to instantiate a new object (and remember, it must be explicitly told to do so...), it basically does two things in this order:
  1. It allocates a storage block of the appropriate size and (IIRC) sets it to zero.
  2. It invokes the constructor, if any, which usually invokes all the other constructors up the class-hierarchy chain.
More than one constructor can be defined, depending on the argument-list (if any...) that is provided, but the essential purpose is always exactly the same: "I have allocated a storage block for you... now, get it ready for use... whatever that may mean to you. (Hey, gimme a break, I'm just a programming-language... I have no idea.)"

A destructor, of course, is the opposite: "I'm getting ready to destroy this storage-block. If it refers to anything else that needs to be terminated or destroyed, please do so now."

Last edited by sundialsvcs; 08-20-2012 at 07:27 PM.
 
Old 08-21-2012, 06:43 AM   #8
johnsfine
LQ Guru
 
Registered: Dec 2007
Distribution: Centos
Posts: 5,286

Rep: Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197Reputation: 1197
Quote:
Originally Posted by sundialsvcs View Post
It allocates a storage block of the appropriate size and (IIRC) sets it to zero.
No, it doesn't set it to zero.

The OS sets memory to zero before giving memory to the process (excepting cases where the memory is given with predefined contents, such as a file mapping).

In a simple program, the memory used within the process, (heap, stack, static or global) for a new object is typically memory the run time library has received zero filled from the OS, so it is typically zero before the constructor is executed, suppressing the symptoms of many common bugs in classes that don't initialize everything they should in their constructors.

But in more complex programs, memory for a new object (heap or stack) is more typically memory released from some earlier use within the same process, not zero filled memory newly received from the OS, so those bugs start to have symptoms.
 
Old 08-21-2012, 08:12 AM   #9
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,610
Blog Entries: 4

Rep: Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905Reputation: 3905
Quote:
Originally Posted by johnsfine View Post
No, it doesn't set it to zero.

The OS sets memory to zero before giving memory to the process (excepting cases where the memory is given with predefined contents, such as a file mapping).

In a simple program, the memory used within the process, (heap, stack, static or global) for a new object is typically memory the run time library has received zero filled from the OS, so it is typically zero before the constructor is executed, suppressing the symptoms of many common bugs in classes that don't initialize everything they should in their constructors.

But in more complex programs, memory for a new object (heap or stack) is more typically memory released from some earlier use within the same process, not zero filled memory newly received from the OS, so those bugs start to have symptoms.
Ahh, drat. Because the Delphi language (in Win32), and the C# follow-on language (designed by the same guy ...) does set the entire memory space of a newly-minted object to known-zeros. I was under the impression for some reason that C++ did the same. Anyhow, it is hugely beneficial IMHO when a language is architected to do this for you: all local-variables are zero / false / empty-string, guaranteed. And it basically only requires that the language's runtime system uses calloc instead of malloc calls internally ...

Last edited by sundialsvcs; 08-21-2012 at 08:14 AM.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
relating to class constructors c++ vendtagain Programming 1 12-21-2009 09:59 AM
c++ and overload of constructors i92guboj Programming 13 09-28-2009 03:24 PM
Purpose of explicit copy constructors (untrustworthy implicit copy constructors?) jgombos Programming 5 03-04-2008 09:23 PM
c# constructors and destructors???!!!?? trscookie Programming 2 06-15-2006 04:21 AM
what are c++ static constructors/destructors? cybercop12us Programming 2 01-24-2003 03:31 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 04:23 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration