Object-Oriented Programming: Dynamic Memory. Copy Constructor, Destructor (1/2)

 

Today we are going to talk about two special member functions in object-oriented systems: copy constructor and destructor.  In C++, these two functions are parts of what's called the Rule of Three.  This rule is a rule of thumb in C++ for building exception-safe code and for successful memory management.

The Rule of Three states that if a class defines one of the following methods, it should probably define all three:

  • Copy constructor
  • Assignment operator
  • Destructor
The rule is based on the fact that automatically generated, implicit versions of these methods exist.  If one of them needs to be defined by the programmer, that means that the implicit version did not fit the program's needs; therefore, the same will probably also be true for the other two methods.

 

We will be discussing the copy constructor and the destructor.  The assignment operator will be covered in one of the next articles when we introduce operator overloading, but for now, it's just important to know about it, and to understand that all three methods need to be defined for very similar reasons.

These reasons will become clear when we explain the concept of shallow copy and deep copy.

One method of copying an object is the shallow copy.  For example, let's say we want to make a copy of object A.  A new object B is created, and the fields' values of A are copied over to B - a bit-wise copy is performed.  However, what happens if our class definition contains complex data structures or has external references such as pointers?  For example, if the field value is a reference to an object (i.e. it holds a memory address), the shallow copy only copies the reference, hence referring to the same object as A.  The referenced objects are thus shared, so if one of these objects is modified (from A or B), the change is visible in the other.  This can cause real problems, like accidentally deleting objects you were referencing.  This is why deep copying is performed.  

Deep copies copy not only references of the original object, but also copy the objects that are referenced.  This way, there are no shared objects and the possibility of error is smaller.  However, deep copies are also more complicated to write.

Now, let's return to what we started talking about: copy constructors are actually what enables the programmer to make deep copies of objects.  This is necessary when a shallow copy just isn't good enough, and that is, as we mentioned, when our class contains complex data structures or references/pointers.

Let's see how you would write a copy constructor in C++:

MyClass (const MyClass &obj) 
{
   //copy constructor body
}
The above was a common form of the copy constructor in C++.  Here, obj is a reference to an object being used to initialize another object.  This reference is also usually declared const, which will cause the variable to be passed without copying but also stop it from then being altered.  Full meaning and usage of the const keyword would exceed the limits of this article; in the context of parameter passing it is also a subject of debate in the C++ community.  For now, we will just consider the example above as the proper form of a copy constructor.

 

On the other hand, a destructor functions are the "inverse" of constructors.  They are called when objects are destroyed (deallocated).  The destructor is commonly used to "clean up" when an object is no longer necessary.  However, the default destructor may sometimes not be enough - for instance, in the same situations that we mentioned before (when there is any dynamic memory involved).  The typical declaration of a class destructor in C++ would be:
        ~MyClass(){}
    

In the next article, we will continue with explaining dynamic memory management in C++.  We talked about this in the C tutorial, and now we are going to introduce C++'s operators new and delete and see how they are used.  This will also enable us to give meaningful and helpful examples of the copy constructor and destructor, so stay tuned!

5 Small Business Marketing Ideas that Won’t Break the Bank

It’s commonly assumed that to market your business effectively, you need to spend lots of money.  While a large marketing budget can be useful, small business owners will be happy to know that it isn’t imperative for successful marketing.  Instead, consider trying some of these free ideas that are sure to increase your sales.

  1. Cross-Marketing – Consider partnering with someone who offers complementary services so that you can promote each other’s businesses.  For example, a mortgage broker, realtor, and home appraiser might team up and agree to refer clients to each other.

  2. Help a Reporter Out – Want free exposure for yourself or your business?  Try HARO, which stands for Help a Reporter Out.  On Nasdaq.com, digital PR firm owner Kari DePhillips says, “HARO is, hands down, the best tool you can use to regularly get in front of journalists who cover your industry.  If you regularly read and respond to HARO queries, you WILL get coverage—if not of your business or service, of your expertise in the industry.  We’ve used HARO to get our clients in publications like the Wall Street Journal, Huffington Post, CNN, the Today Show and many, many more.  And it’s free.”

  3. Start a Meetup – Many small business owners have used meetup.com to great success.  If you provide a service, you may want to create a meetup that is bound to attract people who your service appeals to.  For instance, a therapist might create a group geared toward people who have an interest in personal development.

  4. Guest Blog on Industry Sites – Guest blogging can be a great way to get more traffic on your website.  Simply find an industry website that gets a fair amount of blog traffic and write a guest post.  Oftentimes, blog readers will end up visiting your own web site.

  5. Market Companion Products or Services – As an article on Entrepreneur.com puts it, the phrase “Would you like fries with that?” rakes in a huge additional profit for McDonald’s.  Think of ways that you can leverage sales among your existing customers by upselling them or offering them companion products or services at their time of checkout.   

Thought For The Day

“No matter how correct a mathematical theorem may appear to be, one ought never to be satisfied that there was not something imperfect about it until it also gives the impression of being beautiful.”
George Boole

 

 

Mindfulness Improves Work Performance

You don’t often hear mindfulness mentioned in the workplace but perhaps you should.  Mindfulness can be defined as paying attention non-judgmentally in the present moment, identifying and controlling your emotions, and being aware of how your actions impact others.  Once considered too “out there” for many business people, the benefits of mindfulness are making it an increasingly popular practice.

In fact, mindfulness has become so popular that companies like Google, Facebook, Twitter, LinkedIn, Intel, Starbucks and General Mills advocate the value of it, and some of those companies have even developed their own mindfulness programs.  The reasons for the practice’s growing popularity are myriad but can primarily be attributed to the following:

  • Mindfulness improves concentration.  Fortune’s Oliver Ryan reports that after studying the brain activity of Tibetan monks, Dr. Richard Davidson discovered that “the brain functioning of serious meditators is ‘profoundly different’ from that of nonmeditators – in ways that suggest an elevated capacity to concentrate and to manage emotions.”

  • Mindfulness reduces stress.  Research has shown that those who meditate have a reduction of grey matter in the amygdala, a region associated with stress and anxiety.

  • Mindfulness prevents burnout.  The physician occupation is one that is associated with a high rate of burnout; anywhere from one-third to one-half of doctors suffer from it.  Yet a study published in the Journal of the American Medical Association reported that physicians who practice mindfulness experience less burnout.

  • Mindfulness increases creativity.  Intel began a mindfulness program and when it concluded, participants reported an increase in new ideas, insights, mental clarity, and creativity.

As you can see, mindfulness offers a number of benefits that can boost workplace performance.  If you’d like to become more mindful, stay tuned!  In a future article, we’ll discuss how you can establish your own mindfulness practice.

Tips for Negotiating Your Salary

Salary negotiations can be fraught with tension, even for veteran job seekers.  However, they don’t have to be.  By keeping the following tips in mind, you’ll be well-prepared to negotiate the next time you receive a job offer:

  • Do Your Homework.  Don’t just rely on the employer’s word when he or she tells you what fair compensation is for the position.  Instead, do your research.  Know what similar positions pay in your area, how your unique skillset may increase your worth, and be prepared to articulate your case to your future employer.

  • Don’t Settle.  Too many people accept the first salary offer that comes their way.  However, you should think of this as a starting point.  Employers may deliberately throw out a lower figure, anticipating that future negotiations will take place.

  • Keep Quiet.  Once you’ve presented your case and asked for a higher salary, keep quiet.  Avoid the tendency to ramble nervously or to throw out a lower number if you don’t get an immediate response.  This puts you in a much more powerful position than if you display a lack of confidence by talking too much or quickly backing down.

  • Consider More than Just Salary.  In some cases, your employer may not be able to negotiate on salary.  However, keep in mind that the company may be able to offer you other benefits like extra vacation time, performance bonuses, and severance pay.  Remember to discuss these when you’re negotiating your employment package.

  • Stay Optimistic.  If you remain optimistic, you’ll have greater confidence, and confidence is an asset in any negotiation.  Furthermore, research shows that your optimism is merited.  According to Rania Anderson, author of “Undeterred: The Six Success Habits of Women in Emerging Economies,” “The data shows in the vast majority of cases people who negotiate for a higher salary get one, male or female.  The odds are high that if you ask, you’ll get.”